<?php

function render_tip_firma($select_name, $selected) {	
	  $tip_firma = get_tip_firme();
	  	  
	  echo '<select name="' . $select_name . '" id="' . $select_name . '">';
	  	  
	  foreach ($tip_firma as $key => $value) {
	    if ($value == $selected)
	    	echo '<option value="' . $value . '" selected="selected">' . $key. '</option>';
	    else 
	    	echo '<option value="' . $value . '">' . ($key) . '</option>';
	  }
	  echo '</select>';
}

function get_tip_firme() {
	return $tip_firma = array(LANG_All => CT_TIP_FIRMA_ALL, LANG_FIRMA_TRANSPORTATOR => CT_TIP_FIRMA_TRANSPORTATOR, LANG_FIRMA_SPEDITII => CT_TIP_FIRMA_SPEDITII, LANG_FIRMA_FABRICA => CT_TIP_FIRMA_FABRICA);
}

function render_cont_table($owner, $optiune = null, $currencies, $tip_cont, $obligatoriu = null) {
	require_once('paths.inc');
    require_once(INCLUDE_PATH . 'constants.inc');
	$exista = false;
	for ($i = 0; $i < count($owner->conturi); $i++) {
		if ($owner->conturi[$i]->status != CT_CONT_DELETED) {
			$exista = true;
			break;
		}
	}
	$j = 0;
	
	echo '<table border="0" cellspacing="0" id="wrapper" width="100%">';			
		echo '<thead>';
			echo '<tr>';
				echo '<th colspan="7" align="center">';
					echo LANG_Conturi_firma;
					if ($obligatoriu) echo " " . CT_OBLIGATORIU;
				echo '</th>';				
			echo '</tr>';
		echo '</thead>';
		echo '<tbody>';
		echo '<tr class="capTabel">';
			echo '<td><b>'.LANG_NR_CRT.'</b></td>';
            echo '<td><b>'.LANG_CONT.'</b></td>';
			echo '<td><b>'.LANG_Moneda.'</b></td>';
			echo '<td><b>'.LANG_BANCA.'</b></td>';
			echo '<td><b>'.LANG_SUCURSALA.'</b></td>';			
			if ($optiune != "view") echo '<td colspan="2" align="center"><b>'.LANG_Options.'</b></td>';							
		echo '</tr>';
        
		if ($exista) {
			for ($i = 0; $i < count($owner->conturi); $i++) {
				if ($owner->conturi[$i]->status != CT_CONT_DELETED) {
					$j++;
					echo '<tr class="capTabel">';
						echo "<td>". ($i + 1) . "</td>";
                        echo '<td>'.$owner->conturi[$i]->cont."</td>";
						echo '<td>'.$currencies[$owner->conturi[$i]->moneda]."</td>";
						echo '<td>'.$owner->conturi[$i]->banca."</td>";
						echo '<td>'.$owner->conturi[$i]->sucursala."</td>";
						
						if (empty($optiune)) {
							echo '<td align="center"><input type="button" name="edit" name="edit" value="'.LANG_EDIT.'" onclick="javascript: edit_cont(' . $i . ', ' . $tip_cont . ');" /></td>';
							echo '<td align="center"><input type="button" name="delete" id="delete" value="'.LANG_DELETE.'" onclick="javascript: sterge_cont('.$i.', '.$tip_cont.');" /></td>';				
						}
					echo '</tr>';	
				}
			}
			echo '</tbody>';
		echo '</table>';
	}
    else {
    	echo '<tr class="capTabel">';
    		echo '<td align="center" colspan="7">' . LANG_Nici_un_cont . "</td>";
    	echo "</tr>";
        echo '</table>';
    }
    echo '<span style="display:none" id="contsCount">'.$j.'</span>';
}

function render_adresa_row($adresa, $tip, $tip_loc, $id_rezultat, $i, $render_adresa_row = null) {
    $text = '';
    $text .= '<tr class="capTabel">';
    $j = $i + 1;
    if ($i != -1)
        $text .= "<td>$j</td>";
        
    $text .= '<td>'.$adresa->adresa."</td>";
    $text .= '<td>'.$adresa->oras."</td>";
    $text .= '<td>'.$adresa->judet."</td>";
    $text .= '<td>'.$adresa->cod_postal."</td>";
    $text .= '<td>'.$adresa->tara."</td>";
    if ($render_adresa_row == 1) {
        $text .= '<td>'.getDateForUser($adresa->data)."</td>";
        $text .= '<td>'.getDateForUser($adresa->data_efectiva)."</td>";
        $text .= '<td>'.$adresa->tip_marfa."</td>";
        $text .= '<td>'.$adresa->nr_colete."</td>";
        $text .= '<td>'.$adresa->greutate."</td>";
        $text .= '<td>'.$adresa->alte_mentiuni."</td>";
    }
    
	if ($render_adresa_row != 1) {
		$text .= '<td><input type="button" name="edit" name="edit" value="'.LANG_EDIT.'" onclick="javascript: edit_adresa('.$tip.',' . $tip_loc . ',' . $i . ',\'' . $id_rezultat . '\');" /></td>';
		$text .= '<td><input type="button" name="delete" id="delete" value="'.LANG_DELETE.'" onclick="javascript: sterge_adresa('.$tip.',' . $tip_loc . ',' . $i . ',\'' . $id_rezultat . '\');" /></td>';                
    }
    
    $text .= '</tr>';
    return $text;
}

function render_adresa($comanda, $tip_loc, $tip, $id_rezultat, $for_dispaly_only = null) {	
	require_once("paths.inc");
	require_once(INCLUDE_PATH.'constants.inc');
	
	$j = 0;
	$multe = 0;
	if ($tip_loc == CT_ADRESA_COMANDA_INCARCARE) {
		$adresa = $comanda->adrese_incarcare;     		
	}		
	if ($tip_loc == CT_ADRESA_COMANDA_DESCARCARE) {
		$adresa = $comanda->adrese_descarcare;              
	}		
	if ($tip_loc == CT_ADRESA_COMANDA_VAMA_IMPORT) {
        $adresa = $comanda->adrese_vama_import;             
	}
	if ($tip_loc == CT_ADRESA_COMANDA_VAMA_EXPORT) {
        $adresa = $comanda->adrese_vama_export;             
	}
//	if ($for_dispaly_only == 1)
		echo '<table id="wrapper" style="margin-bottom:3px; margin-top:3px" width="100%">';
//	else
//		echo '<table id="wrapper" style="margin-bottom:3px; margin-top:3px">';
			
	echo '<thead>';
		if (isset($for_dispaly_only) && !empty($for_dispaly_only)) {
			echo '<tr>';
				if ($id_rezultat == "adrese_incarcare")
					echo "<th align=\"center\" colspan=\"12\">" . LANG_Locuri_incarcare . "</th>";
				if ($id_rezultat == "adrese_descarcare")
					echo "<th align=\"center\" colspan=\"12\">" . LANG_Locuri_descarcare . "</th>";				
				if ($id_rezultat == "vama_import")
					echo "<th align=\"center\" colspan=\"12\">" . LANG_Adrese_vama_import . "</th>";
				if ($id_rezultat == "vama_export")
					echo "<th align=\"center\" colspan=\"12\">" . LANG_Adrese_vama_export . "</th>";								
			echo '</tr>';
		}
		echo '<tr>';                           
			echo "<th>".LANG_NUMAR."</th>";
			echo '<th>'.LANG_ADRESA.'</th>';
			echo '<th>'.LANG_ORAS.'</th>';
			echo '<th>'.LANG_JUDET.'</th>';			
			echo '<th>'.LANG_COD_POSTAL.'</th>';			
			echo '<th>'.LANG_TARA.'</th>';
			if ($for_dispaly_only == 1) {
			    echo '<th>'.LANG_DATA_PROGRAMATA.'</th>';
			    echo '<th>'.LANG_DATA_REALIZATA.'</th>';
			    echo '<th>'.LANG_Tip_marfa.'</th>';
			    echo '<th>'.LANG_Nr_colete.'</th>';
			    echo '<th>'.LANG_Greutate.'</th>';
			    echo '<th>'.LANG_Alte_mentiuni.'</th>';
			}
			if ($for_dispaly_only != 1)           
				echo '<th colspan="2">'.LANG_Options.'</th>';		
		echo '</tr>';            
	echo '</thead>';
	
	if (is_array($adresa))
	for ($i = 0; $i < count($adresa); $i++) {
		if ($adresa[$i]->status != CT_ADDRESS_DELETED) {
			$j++;
			echo render_adresa_row($adresa[$i], $tip, $tip_loc, $id_rezultat, $i, $for_dispaly_only);
		}
	}

	if ($j == 0) {

			echo '<td colspan="4">' . LANG_Nu_exista_nici_o_adresa . "</td>";
	
	}
	echo '</table>';
	if ($tip_loc == CT_ADRESA_COMANDA_INCARCARE)
		echo '<span style="display:none" id="IncarcareCount">'.$j.'</span>';
	if ($tip_loc == CT_ADRESA_COMANDA_DESCARCARE)
		echo '<span style="display:none" id="DescarcareCount">'.$j.'</span>';
            
}

function render_firme_comanda_show_contact($select_name, $firme_array, $selected_id=null, $contact_id) {
	// functia aceasta va arata firmele respective plus 
	// in td-ul cu id $contact_id va arata lista de persoane de contact prin ajax!!
	echo "<select class=\"combobox_firme\" name=\"".$select_name."\" id=\"" . $select_name . "\" onchange=\"javascript: arata_contacte_comanda(this.value,'" .$contact_id . "');\">";
	$i = 0;
	$sel = 0;
	
	if (count($firme_array) > 0) {
		foreach ($firme_array as $firma) {
			$text_calitate = "";
			switch ($firma->calitate_firma) {
				case CT_FIRMA_NESERIOASA:
				$text_calitate = " (" . LANG_Firma_neserioasa . ")";
				break;
			}
		  
			if ($firma->id_firma == $selected_id) {
				$sel = $i;              
				echo '<option value="'.$firma->id_firma.'" selected="selected">' . $firma->nume . "$text_calitate" .  '</option>';
			}
			else 
				echo '<option value="'.$firma->id_firma.'">'.$firma->nume . "$text_calitate" . '</option>';
			$i++;
		}
	}
	else echo "<option value=\"-1\">" . LANG_Nici_o_firma . "</option>";
	echo '</select>';
    return $sel;
}

function render_stare_incasare_comanda($select_name, $selected=null) {
	require_once(INCLUDE_PATH.'/constants.inc');
		
	echo '<select name="'.$select_name.'">';
	
	echo '<option value="'.CT_COMANDA_NEINCASATA.'" '; 
		if ($selected == CT_COMANDA_NEINCASATA) echo 'selected="selecte"'; 
	echo '>'.LANG_Comanda_neincasata.'</option>';
	
	echo '<option value="'.CT_COMANDA_INCASATA_PARTIAL.'" '; 
		if ($selected == CT_COMANDA_INCASATA_PARTIAL) echo 'selected="selecte"'; 
	echo '>'.LANG_Comanda_incasata_partial.'</option>';
	
	echo '<option value="'.CT_COMANDA_INCASATA.'" '; 
		if ($selected == CT_COMANDA_INCASATA) echo 'selected="selecte"'; 
	echo '>'.LANG_Comanda_incasata.'</option>';
	
	echo '</select>';
}

function render_contact_table($firma, $optiune = null) {
	
	//vad prima data cate contacte sunt nesterse!!
	
	$exista = false;
	for ($i = 0; $i < count($firma->contacte); $i++) {
		if ($firma->contacte[$i]->status != CT_CONTACT_DELETED) {
			$exista = true;
			break;
		}
	}
	$j = 0;
	
	echo '<table border="0" cellspacing="0" id="wrapper" width="100%">';
		echo "<thead>";
			echo "<tr>";
				echo "<th colspan=\"10\" align=\"center\">";
					echo LANG_Contacte;
				echo "</th>";				
			echo "</tr>";
		echo "</thead>";
		echo "<tbody>";
		echo '<tr class="capTabel">';
			echo '<td><b>'.LANG_NR_CRT.'</b></td>';
			echo '<td><b>'.LANG_NUME_CONTACT.'</b></td>';
			echo '<td><b>'.LANG_SEX_CONTACT.'</b></td>';
			echo '<td><b>'.LANG_FUNCTIE_CONTACT.'</b></td>';			
			echo '<td><b>'.LANG_TEL_FIX_CONTACT.'</b></td>';			
			echo '<td><b>'.LANG_TEL_FAX_CONTACT.'</b></td>';			
			echo '<td><b>'.LANG_TEL_MOBIL_CONTACT.'</b></td>';			
			echo '<td><b>'.LANG_EMAIL_CONTACT.'</b></td>';			
			if ($optiune != "view") echo '<td colspan="2" align="center"><b>'.LANG_Options.'</b></td>';			
		echo '</tr>';
        
	if ($exista) {
		for ($i = 0; $i < count($firma->contacte); $i++) {
			if ($firma->contacte[$i]->status != CT_CONTACT_DELETED) {	
                $j++;
				echo '<tr class="capTabel">';
					echo "<td>" . ($i + 1) . "</td>";
					echo '<td>'.$firma->contacte[$i]->nume."</td>";
					
					if ($firma->contacte[$i]->sex == CT_SEX_MASCULIN) {
						echo '<td>'.LANG_SEX_MALE."</td>";
					}
					else {
						echo '<td>'.LANG_SEX_FEMALE."</td>";
					}
					echo '<td>'.$firma->contacte[$i]->functie."</td>";
					echo '<td>'.$firma->contacte[$i]->tel_fix."</td>";
					echo '<td>'.$firma->contacte[$i]->tel_fax."</td>";
					echo '<td>'.$firma->contacte[$i]->tel_mobil."</td>";
					echo '<td>'.$firma->contacte[$i]->email."</td>";
					
					//transmit $i ca sa stiu ca al i-lea contact din array se va modifica/sterge				
					if (empty($optiune)) {
						echo '<td align="center"><input type="button" name="edit" name="edit" value="'.LANG_EDIT.'" onclick="javascript: edit_contact(' . $i . ');" /></td>';
						echo '<td align="center"><input type="button" name="delete" id="delete" value="'.LANG_DELETE.'" onclick="javascript: sterge_contact('.$i.');" /></td>';				
					}
				echo '</tr>';	
			}				
		}
		echo "</tbody>";
		echo '</table>';        
	}
    else {
    	echo '<tr class="capTabel">';
    		echo '<td align="center" colspan="10">' . LANG_Nici_un_contact . "</td>";
    	echo "</tr>";    	
        echo '</table>';
    }
    echo '<span style="display:none" id="contactsCount">'.$j.'</span>';
}

function render_rute_table($firma, $optiune = null) {
	
	//vad prima data cate contacte sunt nesterse!!
	
	$exista = false;
	for ($i = 0; $i < count($firma->rute); $i++) {
		if ($firma->rute[$i]->status != CT_RUTA_FIRMA_DELETED) {
			$exista = true;
			break;
		}
	}
	$j = 0;

	echo '<table border="0" cellspacing="0" id="wrapper" width="100%">';
		echo "<thead>";
			echo "<tr>";
				echo "<th colspan=\"5\" align=\"center\">";
					echo LANG_Rute;
				echo "</th>";				
			echo "</tr>";
		echo "</thead>";
		echo "<tbody>";
		echo '<tr class="capTabel">';
			echo '<td><b>'.LANG_NR_CRT.'</b></td>';
			echo '<td><b>'.LANG_Loc1.'</b></td>';
			echo '<td><b>'.LANG_Loc2.'</b></td>';
			if ($optiune != "view") echo '<td colspan="2" align="center"><b>'.LANG_Options.'</b></td>';			
		echo '</tr>';
        
	if ($exista) {
		for ($i = 0; $i < count($firma->rute); $i++) {
			if ($firma->rute[$i]->status != CT_RUTA_FIRMA_DELETED) {	
                $j++;
				echo '<tr class="capTabel">';
					echo "<td>" . ($i + 1) . "</td>";
					echo '<td>'.$firma->rute[$i]->loc1."</td>";
					echo '<td>'.$firma->rute[$i]->loc2."</td>";

					//transmit $i ca sa stiu ca al i-lea contact din array se va modifica/sterge				
					if (empty($optiune)) {
						echo '<td align="center"><input type="button" name="edit" name="edit" value="'.LANG_EDIT.'" onclick="javascript: edit_ruta_firma(' . $i . ');" /></td>';
						echo '<td align="center"><input type="button" name="delete" id="delete" value="'.LANG_DELETE.'" onclick="javascript: sterge_ruta_firma('.$i.');" /></td>';				
					}
				echo '</tr>';	
			}				
		}
		echo "</tbody>";
		echo '</table>';        
	}
    else {
    	echo '<tr class="capTabel">';
    		echo '<td align="center" colspan="5">' . LANG_Nici_un_ruta . "</td>";
    	echo "</tr>";    	
        echo '</table>';
    }
    echo '<span style="display:none" id="ruteCount">'.$j.'</span>';
}

function create_new_contact($contact_name, $contact_sex, $contact_functie, $contact_tel_fix, $contact_tel_fax, $contact_tel_mobil, $contact_email, $optiune, $index) {
	if ($optiune == "insert") {
		$contact = new Contact($_SESSION['firma']->id_firma, $contact_name, $contact_sex, $contact_functie,$contact_tel_fix, $contact_tel_fax, $contact_tel_mobil, $contact_email);	
		array_push($_SESSION['firma']->contacte, $contact);		
	}
    
	if ($optiune == "update") {
		$_SESSION['firma']->contacte[$index]->status = CT_CONTACT_MODIFIED;		
		$_SESSION['firma']->contacte[$index]->nume = $contact_name;		
		$_SESSION['firma']->contacte[$index]->sex = $contact_sex;		
		$_SESSION['firma']->contacte[$index]->functie = $contact_functie;		
		$_SESSION['firma']->contacte[$index]->tel_fix = $contact_tel_fix;		
		$_SESSION['firma']->contacte[$index]->tel_fax = $contact_tel_fax;		
		$_SESSION['firma']->contacte[$index]->tel_mobil = $contact_tel_mobil;		
		$_SESSION['firma']->contacte[$index]->email = $contact_email;		
	}
}       

function create_new_ruta_firma($ruta_loc1, $ruta_loc2, $optiune, $index) {
	if ($optiune == "insert") {
		$ruta = new RutaFirma($_SESSION['firma']->id_firma, $ruta_loc1, $ruta_loc2);	
		array_push($_SESSION['firma']->rute, $ruta);		
	}
    
	if ($optiune == "update") {
		$_SESSION['firma']->rute[$index]->status = CT_RUTA_FIRMA_MODIFIED;		
		$_SESSION['firma']->rute[$index]->loc1 = $ruta_loc1;
		$_SESSION['firma']->rute[$index]->loc2 = $ruta_loc2;				
	}	
}

function create_new_cont($cont, $banca, $sucursala, $moneda, $optiune, $index, $tip_cont) {
	if ($optiune == "insert") {
        if ($tip_cont == CT_CONT_CLIENT) {
            $cont = new Cont($_SESSION['client']->id_client, CT_CONT_CLIENT, $cont, $banca, $sucursala, $moneda);    
            array_push($_SESSION['client']->conturi, $cont);        
        }
        else {
		    $cont = new Cont($_SESSION['firma']->id_firma, CT_CONT_FIRMA, $cont, $banca, $sucursala, $moneda);	
		    array_push($_SESSION['firma']->conturi, $cont);		
        }
	}
	if ($optiune == "update") {		
        if ($tip_cont == CT_CONT_CLIENT) {
		    $_SESSION['client']->conturi[$index]->status = CT_CONT_MODIFIED;        
            $_SESSION['client']->conturi[$index]->banca = $banca;        
            $_SESSION['client']->conturi[$index]->cont = $cont;        
            $_SESSION['client']->conturi[$index]->moneda = $moneda;        
            $_SESSION['client']->conturi[$index]->sucursala = $sucursala;
        }
        else {
            $_SESSION['firma']->conturi[$index]->status = CT_CONT_MODIFIED;        
            $_SESSION['firma']->conturi[$index]->banca = $banca;        
            $_SESSION['firma']->conturi[$index]->cont = $cont;        
            $_SESSION['firma']->conturi[$index]->moneda = $moneda;        
            $_SESSION['firma']->conturi[$index]->sucursala = $sucursala;        
        }
	}
	//var_dump($_SESSION['client']);
}

function create_new_address($tip, $tip_loc, $optiune, $adresa, $oras, $judet, $cod_postal, $tara, $nume_firma, $impexp, $index
                            , $data, $data_efectiva, $nume_contact, $tel_contact, $alte_mentiuni, $nume_birou_vamal, $cod_vama
                            , $tip_marfa, $nr_colete, $greutate, $legatura_incarcare) {	
	
	if ($optiune == "insert") {
		
		$adresa = new Address($tip, $adresa, $oras, $judet, $cod_postal, $tara, $nume_firma, $tip_loc);	
        $adresa->impexp = $impexp;
        $adresa->data = getDateForServer($data, true);
        $adresa->data_efectiva = getDateForServer($data_efectiva, true);
        $adresa->alte_mentiuni = $alte_mentiuni;
        $adresa->cod_vama = $cod_vama;
        $adresa->greutate = $greutate;
        $adresa->nr_colete = $nr_colete;
        $adresa->nume_birou_vamal = $nume_birou_vamal;
        $adresa->nume_contact = $nume_contact;
        $adresa->tel_contact = $tel_contact;
        $adresa->tip_marfa = $tip_marfa;
        $adresa->legatura_incarcare = $legatura_incarcare;
		
		$adresa->id_owner = $_SESSION['comanda']->id_comanda;
		if ($tip_loc == CT_ADRESA_COMANDA_VAMA_IMPORT) {
			$_SESSION['comanda']->adrese_vama_import[] = $adresa;
		}		
		if ($tip_loc == CT_ADRESA_COMANDA_VAMA_EXPORT) {
			$_SESSION['comanda']->adrese_vama_export[] = $adresa;
		}						
		if ($tip_loc == CT_ADRESA_COMANDA_INCARCARE) {
			$_SESSION['comanda']->adrese_incarcare[] = $adresa;
		}						
		if ($tip_loc == CT_ADRESA_COMANDA_DESCARCARE) {
			$_SESSION['comanda']->adrese_descarcare[] = $adresa;
		}				
	}	
	if ($optiune == "update") {
		if ($tip_loc == CT_ADRESA_COMANDA_VAMA_IMPORT) {
			$_SESSION['comanda']->adrese_vama_import[$index]->status = CT_ADDRESS_MODIFIED;
			$_SESSION['comanda']->adrese_vama_import[$index]->adresa = $adresa;
			$_SESSION['comanda']->adrese_vama_import[$index]->oras = $oras;
			$_SESSION['comanda']->adrese_vama_import[$index]->judet = $judet;
			$_SESSION['comanda']->adrese_vama_import[$index]->cod_postal = $cod_postal;
			$_SESSION['comanda']->adrese_vama_import[$index]->tara = $tara;
			$_SESSION['comanda']->adrese_vama_import[$index]->nume_firma = $nume_firma;			
            $_SESSION['comanda']->adrese_vama_import[$index]->impexp = $impexp;            
            $_SESSION['comanda']->adrese_vama_import[$index]->alte_mentiuni = $alte_mentiuni;            
            $_SESSION['comanda']->adrese_vama_import[$index]->cod_vama = $cod_vama;            
            $_SESSION['comanda']->adrese_vama_import[$index]->nume_birou_vamal = $nume_birou_vamal;            
            $_SESSION['comanda']->adrese_vama_import[$index]->nume_contact = $nume_contact;            
            $_SESSION['comanda']->adrese_vama_import[$index]->tel_contact = $tel_contact;
            $_SESSION['comanda']->adrese_vama_import[$index]->legatura_incarcare = $legatura_incarcare;              
		}
		if ($tip_loc == CT_ADRESA_COMANDA_VAMA_EXPORT) {
			$_SESSION['comanda']->adrese_vama_export[$index]->status = CT_ADDRESS_MODIFIED;
			$_SESSION['comanda']->adrese_vama_export[$index]->adresa = $adresa;
			$_SESSION['comanda']->adrese_vama_export[$index]->oras = $oras;
			$_SESSION['comanda']->adrese_vama_export[$index]->judet = $judet;
			$_SESSION['comanda']->adrese_vama_export[$index]->cod_postal = $cod_postal;
			$_SESSION['comanda']->adrese_vama_export[$index]->tara = $tara;
            $_SESSION['comanda']->adrese_vama_export[$index]->nume_firma = $nume_firma;            
            $_SESSION['comanda']->adrese_vama_export[$index]->impexp = $impexp;            
            $_SESSION['comanda']->adrese_vama_export[$index]->alte_mentiuni = $alte_mentiuni;            
            $_SESSION['comanda']->adrese_vama_export[$index]->cod_vama = $cod_vama;            
            $_SESSION['comanda']->adrese_vama_export[$index]->nume_birou_vamal = $nume_birou_vamal;            
            $_SESSION['comanda']->adrese_vama_export[$index]->nume_contact = $nume_contact;            
            $_SESSION['comanda']->adrese_vama_export[$index]->tel_contact = $tel_contact;	
            $_SESSION['comanda']->adrese_vama_export[$index]->legatura_incarcare = $legatura_incarcare;              	
		}
		if ($tip_loc == CT_ADRESA_COMANDA_INCARCARE) {
			$_SESSION['comanda']->adrese_incarcare[$index]->status = CT_ADDRESS_MODIFIED;
			$_SESSION['comanda']->adrese_incarcare[$index]->adresa = $adresa;
			$_SESSION['comanda']->adrese_incarcare[$index]->oras = $oras;
			$_SESSION['comanda']->adrese_incarcare[$index]->judet = $judet;
			$_SESSION['comanda']->adrese_incarcare[$index]->cod_postal = $cod_postal;
			$_SESSION['comanda']->adrese_incarcare[$index]->tara = $tara;
            $_SESSION['comanda']->adrese_incarcare[$index]->nume_firma = $nume_firma;       
            $_SESSION['comanda']->adrese_incarcare[$index]->alte_mentiuni = $alte_mentiuni;            
            $_SESSION['comanda']->adrese_incarcare[$index]->nume_contact = $nume_contact;            
            $_SESSION['comanda']->adrese_incarcare[$index]->tel_contact = $tel_contact;        
            $_SESSION['comanda']->adrese_incarcare[$index]->data = getDateForServer($data, true);
            $_SESSION['comanda']->adrese_incarcare[$index]->data_efectiva = getDateForServer($data_efectiva, true);
            $_SESSION['comanda']->adrese_incarcare[$index]->greutate = $greutate;        
            $_SESSION['comanda']->adrese_incarcare[$index]->nr_colete = $nr_colete;        
            $_SESSION['comanda']->adrese_incarcare[$index]->tip_marfa = $tip_marfa;    	
		}
		if ($tip_loc == CT_ADRESA_COMANDA_DESCARCARE) {
			$_SESSION['comanda']->adrese_descarcare[$index]->status = CT_ADDRESS_MODIFIED;
			$_SESSION['comanda']->adrese_descarcare[$index]->adresa = $adresa;
			$_SESSION['comanda']->adrese_descarcare[$index]->oras = $oras;
			$_SESSION['comanda']->adrese_descarcare[$index]->judet = $judet;
			$_SESSION['comanda']->adrese_descarcare[$index]->cod_postal = $cod_postal;
			$_SESSION['comanda']->adrese_descarcare[$index]->tara = $tara;
			$_SESSION['comanda']->adrese_descarcare[$index]->nume_firma = $nume_firma;       
            $_SESSION['comanda']->adrese_descarcare[$index]->alte_mentiuni = $alte_mentiuni;            
            $_SESSION['comanda']->adrese_descarcare[$index]->nume_contact = $nume_contact;            
            $_SESSION['comanda']->adrese_descarcare[$index]->tel_contact = $tel_contact;        
            $_SESSION['comanda']->adrese_descarcare[$index]->data = getDateForServer($data, true);        
            $_SESSION['comanda']->adrese_descarcare[$index]->data_efectiva = getDateForServer($data_efectiva, true);        
            $_SESSION['comanda']->adrese_descarcare[$index]->greutate = $greutate;        
            $_SESSION['comanda']->adrese_descarcare[$index]->nr_colete = $nr_colete;        
            $_SESSION['comanda']->adrese_descarcare[$index]->tip_marfa = $tip_marfa;              
            $_SESSION['comanda']->adrese_descarcare[$index]->legatura_incarcare = $legatura_incarcare;  			
		}
	}
}

// return true if contact is in use and can't be deleted
function sterge_contact($db, $index) {
	if ($_SESSION['firma']->contacte[$index]->status == CT_CONTACT_UNMODIFIED 
		|| $_SESSION['firma']->contacte[$index]->status == CT_CONTACT_MODIFIED) {
		if (Contact::isInUse($db, $_SESSION['firma']->contacte[$index]->id_contact) == true)
			return true;
	}
	$_SESSION['firma']->contacte[$index]->status = CT_CONTACT_DELETED;
	return false;
}

function sterge_adresa($tip, $tip_loc, $index) {
	if ($tip_loc == CT_ADRESA_COMANDA_VAMA_IMPORT) {
		$_SESSION['comanda']->adrese_vama_import[$index]->status = CT_CONTACT_DELETED;	
	}	
	if ($tip_loc == CT_ADRESA_COMANDA_VAMA_EXPORT) {
		$_SESSION['comanda']->adrese_vama_export[$index]->status = CT_CONTACT_DELETED;	
	}	
	if ($tip_loc == CT_ADRESA_COMANDA_INCARCARE) {
        $_SESSION['comanda']->adrese_incarcare[$index]->status = CT_CONTACT_DELETED;
        // Verifica integritatea pt descarcari
        $ind = $index + 1;
        $i = 0;
        foreach($_SESSION['comanda']->adrese_descarcare as $descarcare) {
            if($descarcare->status != CT_CONTACT_DELETED) {
                $aux = explode(";", $descarcare->legatura_incarcare);
                $legatura_incarcare = '';
                for($j = 0; $j < count($aux) - 1; $j++) {
                    if ($aux[$j] < $ind)
                        $legatura_incarcare .= $aux[$j] . ";";
                    if ($aux[$j] > $ind)
                        $legatura_incarcare .= ($aux[$j] - 1). ";";
                }
                $_SESSION['comanda']->adrese_descarcare[$i]->legatura_incarcare = $legatura_incarcare;
            }
            $i++;
        }
        // Verifica integritatea pt vamele_import
        $ind = $index + 1;
        $i = 0;
        foreach($_SESSION['comanda']->adrese_vama_import as $vama_import) {
            if($descarcare->status != CT_CONTACT_DELETED) {
                $aux = explode(";", $vama_import->legatura_incarcare);
                $legatura_incarcare = '';
                for($j = 0; $j < count($aux) - 1; $j++) {
                    if ($aux[$j] < $ind)
                        $legatura_incarcare .= $aux[$j] . ";";
                    if ($aux[$j] > $ind)
                        $legatura_incarcare .= ($aux[$j] - 1). ";";
                }
                $_SESSION['comanda']->adrese_vama_import[$i]->legatura_incarcare = $legatura_incarcare;
            }
            $i++;
        }
        // Verifica integritatea pt vamele_export
        $ind = $index + 1;
        $i = 0;
        foreach($_SESSION['comanda']->adrese_vama_export as $vama_import) {
            if($descarcare->status != CT_CONTACT_DELETED) {
                $aux = explode(";", $vama_import->legatura_incarcare);
                $legatura_incarcare = '';
                for($j = 0; $j < count($aux) - 1; $j++) {
                    if ($aux[$j] < $ind)
                        $legatura_incarcare .= $aux[$j] . ";";
                    if ($aux[$j] > $ind)
                        $legatura_incarcare .= ($aux[$j] - 1). ";";
                }
                $_SESSION['comanda']->adrese_vama_export[$i]->legatura_incarcare = $legatura_incarcare;
            }
            $i++;
        }
	}	
	if ($tip_loc == CT_ADRESA_COMANDA_DESCARCARE) {
		$_SESSION['comanda']->adrese_descarcare[$index]->status = CT_CONTACT_DELETED;	
	}
}

function sterge_cont($index, $tip_cont) {
    if ($tip_cont == CT_CONT_CLIENT)
        $_SESSION['client']->conturi[$index]->status = CT_CONT_DELETED;
    else
	    $_SESSION['firma']->conturi[$index]->status = CT_CONT_DELETED;		
}

function render_sex_select($name, $id, $selected) {
	//name este numele selectului
	//id este id-ul selectului
	//selected este indexul optiunului selectat imiplicit
	//prima optiune este MALE cu valoarea 0
	//a doua optiune este FEMALE cu valoarea 1
	$mes =  "<select name=\"" . $name . "\" id=\"" . $id . "\">";
		if ($selected == 0) $mes .= "<option selected=\"selected\" value=\"0\">" . LANG_SEX_MALE . "</option>";
		else $mes .= "<option value=\"0\">" . LANG_SEX_MALE . "</option>";
		if ($selected == 1) $mes .= "<option selected=\"selected\" value=\"1\">" . LANG_SEX_FEMALE . "</option>";
		else $mes .= "<option value=\"1\">" . LANG_SEX_FEMALE . "</option>";
	$mes .= "</select>";
	return $mes;
}

function render_contact_select_comanda($id_firma, $id_contact, $db, $name_select) {
	$contacts = Contact::queryLoadByFirma($db, $id_firma);
	
	//are numele implicit de id_contact_sol deoarece asa il preiau din post din add_comanda.php
    $text = '';
    $text .= "<select class=\"combobox_contact\" name=\"" . $name_select . "\" id=\"" . $name_select . "\" onChange=\"seteazaHidden(); \">";

    if (count($contacts) > 0) {
		for ($i = 0; $i < count($contacts); $i++) {
	            $sel = '';
	            if ($id_contact == $contacts[$i]->id_contact) {
	                $sel = ' selected="selected" ';
	            }
			$text .= "<option value=\"" . $contacts[$i]->id_contact . "\" $sel>" . $contacts[$i]->nume . "</option>";
		}
    }
    else $text .= "<option value=\"-1\">" . LANG_Nici_un_contact . "</option>";
	$text .= "</select>";
    echo $text;
}

function get_firme($db, $id_client, $pagina, $per_pag, $camp, $order = null, $user, $keyword, $tip_firma = null, $camp_order = null, $val1 = null, $val2 = null) {
	
	try {
		$coloane_firme = $user->coloane_firme;
		$coloane = explode(",", $coloane_firme);
		
		$firme = array();
        $conditie = " id_client = $id_client ";
		if (substr($tip_firma, 0, 2) == 'cf') {
			// adica a avut loc o filtrare dupa moderearea firmei: gen serioasa, neserioasa
			$moderate_filtru = substr($tip_firma, 2);
			$conditie .= " AND firme.calitate_firma = $moderate_filtru ";
		}
        else {
        	if ($tip_firma != -1 && isset($tip_firma) && $tip_firma != 3) $conditie .= " AND firme.tip = $tip_firma "; 
        }
        
		if ($camp == -1 && isset($keyword) && !empty($keyword)) {
             $conditie .= " AND (LOWER(firme.nume) LIKE '%" . $keyword . "%' OR 
                                 LOWER(firme.cf) LIKE '%" . $keyword . "%' OR 
                                 LOWER(firme.rc) LIKE '%" . $keyword . "%' OR 
                                 LOWER(firme.tel_fix) LIKE '%" . $keyword . "%' OR
             					 LOWER(firme.tel_fax) LIKE '%" . $keyword . "%' OR
             					 LOWER(firme.tel_mobil) LIKE '%" . $keyword . "%' OR
             					 LOWER(firme.email) LIKE '%" . $keyword . "%' OR
             					 LOWER(firme.web) LIKE '%" . $keyword . "%')"; 
		}
		else if ($camp != -1 && isset($keyword) && !empty($keyword) && substr($camp,0,1) != '1'){
		    $conditie .= " AND LOWER(firme.$camp) LIKE '%" . $keyword . "%'";
		}
		
		//in caz ca coloana dupa care s-a sortat a fost scoasa atunci punem implicit dupa nume pentru ca tot timpul numele
		//este afisat implicit, si ordinea sa fie asc;
				
		if (!in_array($camp_order, $coloane)) {
			$camp_order = 'nume';
			$order = "ASC";
		}

		$arr = Firma::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina, $per_pag, $conditie, $camp, $order, $keyword, $camp_order, $val1, $val2);
		$firme = $arr['firme'];
		$adrese = $arr['adrese'];
		$pagina_curenta = $pagina;
		
		
		if (empty($firme)) {
			//inseamna ca pe pagina asta nu se afla nimic
			if ($pagina != 0) {
				$arr = Firma::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina-1, $per_pag, $conditie, $camp, $order, $keyword, $camp_order, $val1, $val2);
				$firme = $arr['firme'];
				$adrese = $arr['adrese'];
				$pagina_curenta = $pagina - 1;
			}
		}
								
		$text = "";
		$text .= "<div id=\"firme_list\">";
			$text .= "<table id=\"wrapper\" width=\"100%\">";
			
			$total = $arr['total'];
			$nr_coloane = count($coloane);
			
			if ($nr_coloane == 1) $colspan = $nr_coloane + 2;
			else $colspan = $nr_coloane + 1;
			$text .= "<thead>";
				$text .= "<tr>";
					$text .= "<th colspan=\"" . ($colspan) . "\">" . LANG_Firme . "</th>";
				$text .= "</tr>";						
			$text .= "</thead>";
			$text .= "<tr class=\"paginare\">";
                $text .= "<td colspan=\"{$colspan}\">";									
				    $text .= render_pagini_firma($total, $per_pag, $id_client, $camp, $order, $pagina_curenta, $user->coloane_firme, $keyword, $tip_firma, $camp_order);										
                $text .= "</td>";
			$text .= "</tr>";						
									
			
			$text .= "<tr class=\"capTabel\">";
				$text .= "<td>
								<a onclick=\"javascript: custom_field_firm('save_render');\">
									<img border=\"0\" src=\"" . IMG_PATH . "/select_field.png\" />
								</a>
						  </td>";

				for ($j = 0; $j < $nr_coloane; $j++) {
					$var = "LANG_" . $coloane[$j];
					if ($camp_order == $coloane[$j]) {
						if ($order == 'ASC') {
							$order2 = 'DESC';
							$text_imagine = "<img src=\"" . IMG_PATH . "sortD.jpg\" border=\"0\" />";
							$text .= "<td bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"><a class=\"cap_tabel\" onclick=\"javascript: sorteaza_firme('" . $coloane[$j] . "',$per_pag, $id_client, '$camp', '$order2', $pagina_curenta, '{$user->coloane_firme}', '$keyword', $tip_firma);\"><b>" . constant($var) . "</b></a> $text_imagine</td>";
						}
						else {
							$order2 = 'ASC';						
							$text_imagine = "<img src=\"" . IMG_PATH . "sortA.jpg\" border=\"0\" />";
							$text .= "<td bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"><a class=\"cap_tabel\" onclick=\"javascript: sorteaza_firme('" . $coloane[$j] . "',$per_pag, $id_client, '$camp', '$order2', $pagina_curenta, '{$user->coloane_firme}', '$keyword', $tip_firma);\"><b>" . constant($var) . "</b></a> $text_imagine</td>";
						}
					}
					else {
						$order2 = 'ASC';															
						$text .= "<td><a class=\"cap_tabel\" onclick=\"javascript: sorteaza_firme('" . $coloane[$j] . "',$per_pag, $id_client, '$camp', '$order2', $pagina_curenta, '{$user->coloane_firme}', '$keyword', $tip_firma);\"><b>" . constant($var) . "</b></a></td>";
					}									
				}
				
				if ($nr_coloane == 1) $text .= "<td></td>";
			$text .= "</tr>";	
			
			for ($i = 0; $i < $per_pag; $i++) {
				if (!empty($firme[$i]->id_firma)) {
					$text .= "<tr class=\"blueThing\" onclick=\"set_firme_row_and_click(" . $i . ")\" onMouseOver=\"this.className = 'whiteThing';\" onMouseOut =\"this.className = 'blueThing'\">";
						
						$text .= "<td align=\"center\" width=\"20\">
										<input onclick=\"javascript: bifeaza();\" type=\"checkbox\" name=\"ch" . $i . "\" value=\"" . $firme[$i]->id_firma . "\" id=\"ch" . $i . "\"/>
								  </td>";
						
						for ($j = 0; $j < $nr_coloane; $j++) {
							if ($coloane[$j] == $camp_order) $bgcolor = "bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"";
							else $bgcolor = ""; 
							if ($coloane[$j] == 'nume') {
								$text .= "<td $bgcolor><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">" . $firme[$i]->$coloane[$j] . "</a></td>";
							}
							else if ($coloane[$j] == 'oras') {
								$text .= "<td $bgcolor><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">" . $adrese[$i]->oras . "</a></td>";
							}
							else if ($coloane[$j] == 'tara') {
								$text .= "<td $bgcolor><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">" . $adrese[$i]->tara . "</a></td>";
							}
							else if ($coloane[$j] == 'tip') {
								$text .= "<td $bgcolor><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">";
								
								switch ($firme[$i]->tip) {
									case CT_TIP_FIRMA_FABRICA: {
										$text .=  LANG_FIRMA_FABRICA;
										break;
									}
									case CT_TIP_FIRMA_SPEDITII: {
										$text .=  LANG_FIRMA_SPEDITII;
										break;
									}
									case CT_TIP_FIRMA_TRANSPORTATOR: {
										$text .=  LANG_FIRMA_TRANSPORTATOR;
										break;
									}
									case CT_TIP_FIRMA_ALL: {
										$text .=  LANG_All;
										break;
									}
								}
								$text .=  "</a></td>";
							}		
							else if ($coloane[$j] == 'Calitate_firma') {
								$text .= "<td $bgcolor><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">";
								
								switch ($firme[$i]->calitate_firma) {
									case CT_FIRMA_SERIOASA: {
										$text .=  LANG_Firma_serioasa;
										break;
									}
									case CT_FIRMA_NESERIOASA: {
										$text .=  LANG_Firma_neserioasa;
										break;
									}
								}
								$text .=  "</a></td>";								
							}
							else {                                
								$nume_var = "LANG_" . $firme[$i]->$coloane[$j];
								$text .= "<td $bgcolor>" . $firme[$i]->$coloane[$j] . "</td>";
							}
							
							if ($nr_coloane == 1) $text .= "<td></td>";
						}											
					$text .= "</tr>";	
				}						
			}
			if ($order == 'ASC') $order = 'DESC'; else $order = 'ASC';		
			$text .= "</table>";
			$text .= "<input type=\"hidden\" name=\"pagina\" id=\"pagina\" value=\"$pagina_curenta\" />";						
			$text .= "<input type=\"hidden\" name=\"per_pag\" id=\"per_pag\" value=\"$per_pag\" />";						
			$text .= "<input type=\"hidden\" name=\"id_client\" id=\"id_client\" value=\"$id_client\" />";						
			$text .= "<input type=\"hidden\" name=\"tip_firma_f\" id=\"tip_firma_f\" value=\"$tip_firma\" />";
			$text .= "<input type=\"hidden\" name=\"camp\" id=\"camp\" value=\"$camp\" />";						
			$text .= "<input type=\"hidden\" name=\"camp_order\" id=\"camp_order\" value=\"$camp_order\" />";
			$text .= "<input type=\"hidden\" name=\"order\" id=\"order\" value=\"$order\" />";
			$text .= "<input type=\"hidden\" name=\"coloane_firme\" id=\"coloane_firme\" value=\"$user->coloane_firme\" />";
			$text .= "<input type=\"hidden\" name=\"keyword\" id=\"keyword\" value=\"$keyword\" />";									
		$text .= "</div>";
		
		$arr = array();
		$arr[0] = $text;
		$arr[1] = $total;
		return $arr; 
		
	}
	catch (QueryLoadFirmaException $e) {
		echo "failed";
		return false;
	}
}

/*
 * @param date $date the date that needs to be checked if it is for real a date
 * @return string the date for the server
 */

function check_is_date_for_user($date) {
	 $nr_matching = preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/', $date);
	 if ($nr_matching == 1) return 1;
	 else return 0;	 			 
}
         
function get_comenzi($db, $pagina, $per_pag, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp = null, $order = null, $coloane_comenzi, $pret_min=null, $pret_max=null, $cost_min=null, $cost_max=null, $data_scadenta_sol1=null, $data_scadenta_sol2=null, $data_scadenta_exec1=null, $data_scadenta_exec2=null, $data_factura_sol1=null, $data_factura_sol2=null, $data_factura_exec1=null, $data_factura_exec2=null, $sc_incasare=null, $sc_plata=null, $cond_firme=null, $camp_sort=null, $currencies = null, $sau_si = null) {
	 $id_client = $_SESSION['user_logat']->id_client;
	 	
	 $nr_matching = preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/', $keyword);
	 
	 if ($nr_matching == 1) {
	 	
		/*
	 	 * inseamna ca a cautat dupa o data si va trebui sa o convertesc in format pentru mysql
	 	 * insa nu a selectat un camp de data din combo box
	 	 * cel mai probabil a selectat in toate si a dat o data ca intrare 
	 	 * convertesc asa aaaa-ll-zz 
	 	 */
	 	
	 	$arr_keyword = explode("-", $keyword);
	 	$keyword = $arr_keyword[2] . "-" . $arr_keyword[1] . "-" . $arr_keyword[0]; 
	 }

	 /*
	  * daca cumva a cautat dupa un camp de data... cu interval trebuie sa convertesc date in
	  * format MYSQL  
	  */
	 
	 if (check_is_date_for_user($val1)) {
	 	$val1 = getDateForServer($val1);
	 	$val1 = "'" . $val1 . "'";	 	
	 }
	 else {
		 $nr_matching = preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $val1);	 
		 if ($nr_matching == 1) {
		 	//data e deja ptr server dar fara '
		 	$val1 = "'" . $val1 . "'";
		 }		 	
	 }
	 if (check_is_date_for_user($val2)) {
	 	$val2 = getDateForServer($val2);
	 	$val2 = "'" . $val2 . "'";
	 		
	 }
	 else {
		 $nr_matching = preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $val2);	 
		 if ($nr_matching == 1) {
		 	//data e deja ptr server dar fara '
		 	$val2 = "'" . $val2 . "'";
		 }	 	
	 }
	 	
	 try {
		$comenzi = array();
		$arr = Comanda::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina, $per_pag, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp, $order, $coloane_comenzi, $pret_min, $pret_max, $cost_min, $cost_max, $data_scadenta_sol1, $data_scadenta_sol2, $data_scadenta_exec1, $data_scadenta_exec2, $data_factura_sol1, $data_factura_sol2, $data_factura_exec1, $data_factura_exec2, $sc_incasare, $sc_plata, $cond_firme, $camp_sort, $sau_si);
		$pagina_curenta = $pagina;
		$comenzi = $arr[0];
        
		if (empty($comenzi)) {			
			//inseamna ca pe pagina asta nu se afla nimic
			if ($pagina != 0) {
				$arr = Comanda::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina-1, $per_pag, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp, $order, $coloane_comenzi, $pret_min, $pret_max, $cost_min, $cost_max, $data_scadenta_sol1, $data_scadenta_sol2, $data_scadenta_exec1, $data_scadenta_exec2, $data_factura_sol1, $data_factura_sol2, $data_factura_exec1, $data_factura_exec2, $sc_incasare, $sc_plata, $cond_firme, $camp_sort, $sau_si);
				$comenzi = $arr[0];
				$pagina_curenta = $pagina - 1;
			}
		}
        
		$coloane = explode(",", $coloane_comenzi);
		
		$text = "";
		if (!in_array($camp_sort, $coloane)) $camp_sort = 'id_firma_sol';
					$text .= "<table align=\"center\" id=\"wrapper\" width=\"100%\">";
					
					$total = $arr[1];
					$nr_coloane = count($coloane);
					$text .= "<thead>";
						$text .= "<tr>";
							$text .= "<th align=\"center\" colspan=\"" . ($nr_coloane + 1) . "\">" . LANG_Comenzi . "</th>";
						$text .= "</tr>";	
					$text .= "</thead>";
                    $text .= "<tr class=\"paginare\">";                                    

					    $text .= "<td align=\"center\" colspan=\"" . ($nr_coloane) . "\">";        
						    $text .= render_pagini_comenzi($total, $per_pag, $id_client, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp, $order, $pagina_curenta, $coloane_comenzi, $pret_min, $pret_max, $cost_min, $cost_max, $data_scadenta_sol1, $data_scadenta_sol2, $data_scadenta_exec1, $data_scadenta_exec2, $data_factura_sol1, $data_factura_sol2, $data_factura_exec1, $data_factura_exec2, $sc_incasare, $sc_plata, $cond_firme, $camp_sort);
                        $text .= "</td>";
                    $text .= "</tr>";						
					$text .= "<tr class=\"capTabel\">";
						$text .= "<td width=\"20\"><a onclick=\"javascript: custom_field_comand('save_render');\"><img border=\"0\" src=\"" . IMG_PATH . "/select_field.png\" /></a></td>";
						
						for ($j = 1; $j < $nr_coloane; $j++) {	
							$var = "LANG_" . $coloane[$j];								
							if (($camp_sort == $coloane[$j]) || ($camp_sort == 'id' && $coloane[$j] == 'id')) {
								if ($order == 'ASC') {
									$order2 = 'DESC';
									$text_imagine = "<img src=\"" . IMG_PATH . "sortD.jpg\" border=\"0\" />";
									$text .= "<td bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"><a class=\"linkComandaCapTabel\" onclick=\"javascript: sorteaza_comenzi('" . $coloane[$j] . "', '" . $order2 . "');\">" . "" . constant($var) . "</a> $text_imagine</td>";
								}
								else {
									$order2 = 'ASC';						
									$text_imagine = "<img src=\"" . IMG_PATH . "sortA.jpg\" border=\"0\" />";
									$text .= "<td bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"><a class=\"linkComandaCapTabel\" onclick=\"javascript: sorteaza_comenzi('" . $coloane[$j] . "', '" . $order2 . "');\">" . "" . constant($var) . "</a> $text_imagine</td>";
								}
							}
							else {
								$order2 = 'ASC';													
								$text .= "<td><a class=\"linkComandaCapTabel\" onclick=\"javascript: sorteaza_comenzi('" . $coloane[$j] . "', '" . $order2 . "');\">" . "" . constant($var) . "</a></td>";
							}							
						}
					$text .= "</tr>";	
					
					for ($i = 0; $i < $per_pag; $i++) {
                        
						if (isset($comenzi[$i]->id_comanda)) {

							$text .= "<tr class=\"blueThing\" onclick=\"set_comenzi_row_and_click(" . $i . ")\" onMouseOver=\"this.className = 'whiteThing';\" onMouseOut =\"this.className = 'blueThing'\">";
								$text .= "<td align=\"center\" width=\"20\">
											<input onclick=\"javascript: bifeaza();\" type=\"checkbox\" name=\"ch" . $i . "\" value=\"" . $comenzi[$i]->id_comanda . "\" id=\"ch" . $i . "\"/>
										  </td>";		
								for ($j = 1; $j < $nr_coloane; $j++) {	
									if ($camp_sort == $coloane[$j]) $bgcolor = "bgcolor=\"" . CT_COLOR_HIGHLIGHT_SORT_COLUMN . "\"";
									else $bgcolor = "";			
									if ($coloane[$j] == 'id_firma_sol') {
										$text .= "<td $bgcolor><a class=\"rowComanda\" href=\"view_firma.php?id=" . $comenzi[$i]->$coloane[$j] . "\">" . $comenzi[$i]->_external_firma_sol . "</a></td>";	
									}
									else if ($coloane[$j] == 'id_firma_exec') {
										$text .= "<td $bgcolor><a class=\"rowComanda\" href=\"view_firma.php?id=" . $comenzi[$i]->$coloane[$j] . "\">" . $comenzi[$i]->_external_firma_exec . "</a></td>";	
									}
									else if ($coloane[$j] == 'id_contact_sol') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . $comenzi[$i]->_external_contact_sol . "</a></td>";	
									}
									else if ($coloane[$j] == 'id_contact_exec') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . $comenzi[$i]->_external_contact_exec . "</a></td>";	
									}
									else if ($coloane[$j] == 'moneda_exec' || $coloane[$j] == 'moneda_sol') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . $currencies[$comenzi[$i]->$coloane[$j]] . "</a></td>";	
									}																		
									else if ($coloane[$j] == 'stare_incasare_sol') {
										if ($comenzi[$i]->$coloane[$j] == 0) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_neincasata) . "</td>";	
										if ($comenzi[$i]->$coloane[$j] == 1) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_incasata_partial) . "</td>";	
										if ($comenzi[$i]->$coloane[$j] == 2) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_incasata) . "</td>";	
									}									
									else if ($coloane[$j] == 'stare_plata_exec') {
										if ($comenzi[$i]->$coloane[$j] == 0) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_neplatita) . "</td>";	
										if ($comenzi[$i]->$coloane[$j] == 1) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_platita_partial) . "</td>";	
										if ($comenzi[$i]->$coloane[$j] == 2) $text .= "<td $bgcolor class=\"rowComanda\">" . (LANG_Comanda_platita) . "</td>";	
									}
//									else if ($coloane[$j] == 'id') $text .= "<td>" . $comenzi[$i]->id_comanda . "</td>";
									else if ($coloane[$j] == '_cmr_exec' || $coloane[$j] == '_factura_exec' || $coloane[$j] == '_carnet_tir_exec' || $coloane[$j] == '_decl_vamala_exec') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . show_status_acte($comenzi[$i]->$coloane[$j]) . "</td>";										
									}									
									else if ($coloane[$j] == '_cmr_sol' || $coloane[$j] == '_factura_sol' || $coloane[$j] == '_carnet_tir_sol' || $coloane[$j] == '_decl_vamala_sol') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . show_status_acte($comenzi[$i]->$coloane[$j]) . "</td>";										
									}
									else if ($coloane[$j] == 'suma_totala_sol' || $coloane[$j] == 'suma_sol' || $coloane[$j] == 'taxe_supl_to_sol' || $coloane[$j] == 'penaliz_from_sol') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . ($comenzi[$i]->$coloane[$j]) . " " . $currencies[$comenzi[$i]->moneda_sol] . "</td>";
									}
									else if ($coloane[$j] == 'suma_totala_exec' || $coloane[$j] == 'suma_exec' || $coloane[$j] == 'taxe_supl_from_exec' || $coloane[$j] == 'penaliz_to_exec') {
										$text .= "<td $bgcolor class=\"rowComanda\">" . ($comenzi[$i]->$coloane[$j]) . " " . ($currencies[$comenzi[$i]->moneda_exec]) . "</td>";
									}				
									else if (substr($coloane[$j],0,4) == 'data') {
										$text .= "<td $bgcolor class=\"rowComanda\">" .  getDateForUser($comenzi[$i]->$coloane[$j]) . "</td>";															
									}
									else $text .= "<td $bgcolor class=\"rowComanda\">" . $comenzi[$i]->$coloane[$j] . "</td>";	
								}
								//pun campuri ascunse pentru suma_totala_sol, suma_totala_exec si monedele respective
								$text .= "<input type=\"hidden\" name=\"suma_totala_sol{$comenzi[$i]->id_comanda}\" id=\"suma_totala_sol{$comenzi[$i]->id_comanda}\" value=\"{$comenzi[$i]->suma_totala_sol}\" />";																		
								$text .= "<input type=\"hidden\" name=\"suma_totala_exec{$comenzi[$i]->id_comanda}\" id=\"suma_totala_exec{$comenzi[$i]->id_comanda}\" value=\"{$comenzi[$i]->suma_totala_exec}\" />";																		
								$text .= "<input type=\"hidden\" name=\"stare_incasare_sol" . $comenzi[$i]->id_comanda . "\" id=\"stare_incasare_sol" . $comenzi[$i]->id_comanda . "\" value=\"{$comenzi[$i]->stare_incasare_sol}\" />";						
								$text .= "<input type=\"hidden\" name=\"stare_plata_exec" . $comenzi[$i]->id_comanda . "\" id=\"stare_plata_exec" . $comenzi[$i]->id_comanda . "\" value=\"{$comenzi[$i]->stare_plata_exec}\" />";														
								$text .= "<input type=\"hidden\" name=\"moneda_sol{$comenzi[$i]->id_comanda}\" id=\"moneda_sol{$comenzi[$i]->id_comanda}\" value=\"{$comenzi[$i]->moneda_sol}\" />";																		
                                $text .= "<input type=\"hidden\" name=\"moneda_exec{$comenzi[$i]->id_comanda}\" id=\"moneda_exec{$comenzi[$i]->id_comanda}\" value=\"{$comenzi[$i]->moneda_exec}\" />";                                                                        
                                $text .= "<input type=\"hidden\" name=\"nr_comanda_exec{$comenzi[$i]->id_comanda}\" id=\"nr_comanda_exec{$comenzi[$i]->id_comanda}\" value=\"{$comenzi[$i]->nr_comanda_exec}\" />";                                                                        
							$text .= "</tr>";	
						}						
					}	
						
					$text .= "<input type=\"hidden\" name=\"camp\" id=\"camp\" value=\"$camp\" />";					
					$text .= "<input type=\"hidden\" name=\"camp_sort\" id=\"camp_sort\" value=\"$camp_sort\" />";					
					$text .= "<input type=\"hidden\" name=\"order_sort\" id=\"order_sort\" value=\"$order\" />";						
					
					$text .= "<input type=\"hidden\" name=\"pagina\" id=\"pagina\" value=\"$pagina_curenta\" />";
						
					$text .= "<input type=\"hidden\" name=\"per_pag\" id=\"per_pag\" value=\"$per_pag\" />";						
					$text .= "<input type=\"hidden\" name=\"id_client\" id=\"id_client\" value=\"$id_client\" />";
					$text .= "<input type=\"hidden\" name=\"total\" id=\"total\" value=\"$total\" />";
					$text .= "<input type=\"hidden\" name=\"comanda_incasata\" id=\"comanda_incasata\" value=\"$comanda_incasata\" />";
					$text .= "<input type=\"hidden\" name=\"comanda_platita\" id=\"comanda_platita\" value=\"$comanda_platita\" />";
					$text .= "<input type=\"hidden\" name=\"scadenta_incasare\" id=\"scadenta_incasare\" value=\"$scadenta_incasare\" />";
					$text .= "<input type=\"hidden\" name=\"scadenta_plata\" id=\"scadenta_plata\" value=\"$scadenta_plata\" />";
					$text .= "<input type=\"hidden\" name=\"f_sol\" id=\"f_sol\" value=\"$f_sol\" />";					
					$text .= "<input type=\"hidden\" name=\"f_exec\" id=\"f_exec\" value=\"$f_exec\" />";
					$text .= "<input type=\"hidden\" name=\"keyword\" id=\"keyword\" value=\"$keyword\" />";
					
					/*
					 * pentru aceste 2 campuri scot ghilimele de inceput si sfarsit 
					 */
					
					$text .= "<input type=\"hidden\" name=\"val1_1\" id=\"val1_1\" value=\"" . str_replace("'", "", $val1) . "\" />";
					$text .= "<input type=\"hidden\" name=\"val2_1\" id=\"val2_2\" value=\"" . str_replace("'", "", $val2) . "\" />";
										
					$text .= "<input type=\"hidden\" name=\"pret_min\" id=\"pret_min\" value=\"$pret_min\" />";					
					$text .= "<input type=\"hidden\" name=\"pret_max\" id=\"pret_max\" value=\"$pret_max\" />";
					$text .= "<input type=\"hidden\" name=\"cost_min\" id=\"cost_min\" value=\"$cost_min\" />";										
					$text .= "<input type=\"hidden\" name=\"cost_max\" id=\"cost_max\" value=\"$cost_max\" />";
					$text .= "<input type=\"hidden\" name=\"data_scadenta_sol1\" id=\"data_scadenta_sol1\" value=\"$data_scadenta_sol1\" />";					
					$text .= "<input type=\"hidden\" name=\"data_scadenta_sol2\" id=\"data_scadenta_sol2\" value=\"$data_scadenta_sol2\" />";					
					$text .= "<input type=\"hidden\" name=\"data_scadenta_exec1\" id=\"data_scadenta_exec1\" value=\"$data_scadenta_exec1\" />";					
					$text .= "<input type=\"hidden\" name=\"data_scadenta_exec2\" id=\"data_scadenta_exec2\" value=\"$data_scadenta_exec2\" />";
					$text .= "<input type=\"hidden\" name=\"data_factura_sol1\" id=\"data_factura_sol1\" value=\"$data_factura_sol1\" />";					
					$text .= "<input type=\"hidden\" name=\"data_factura_sol2\" id=\"data_factura_sol2\" value=\"$data_factura_sol2\" />";										
					$text .= "<input type=\"hidden\" name=\"data_factura_exec1\" id=\"data_factura_exec1\" value=\"$data_factura_exec1\" />";					
					$text .= "<input type=\"hidden\" name=\"data_factura_exec2\" id=\"data_factura_exec2\" value=\"$data_factura_exec2\" />";										
					
					$text .= "<input type=\"hidden\" name=\"sc_incasare\" id=\"sc_incasare\" value=\"$sc_incasare\" />";					
					$text .= "<input type=\"hidden\" name=\"sc_plata\" id=\"sc_plata\" value=\"$sc_plata\" />";					
					$text .= "<input type=\"hidden\" name=\"cond_firme\" id=\"cond_firme\" value=\"$cond_firme\" />";
					$text .= "<input type=\"hidden\" name=\"sau_si\" id=\"sau_si\" value=\"$sau_si\" />";																								
					$text .= "</table>";
		
		$arr = array();
		$arr[0] = $text;
		$arr[1] = $total;
		return $arr; 
		
	}
	catch (QueryLoadComandaException $e) {
		return false;
	}
}

function get_firme_search($db, $id_client, $pagina, $per_pag, $conditie) {
	try {
		$firme = array();
		$arr = Firma::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina, $per_pag, $conditie);
		$firme = $arr[0];
		
		if (empty($firme)) {
			//inseamna ca pe pagina asta nu se afla nimic
			if ($pagina != 0) {
				$arr = Firma::queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $pagina-1, $per_pag, $conditie);
				$firme = $arr[0];
			}
		}
		
		if (!empty($firme)) {
			$coloane_firme = 'nume,email,web,cf,rc,tel_fix,tel_fax,tel_mobil,email,web';
			
			$coloane = explode(",", $coloane_firme);
			
			$text = "";
			$text .= "<div id=\"firme_list\">";
				$text .= "<table>";
				
				$total = $arr[1];
				$nr_coloane = count($coloane);
				
				$text .= "<tr>";
					for ($j = 0; $j < $nr_coloane; $j++) {
						$text .= "<td>" . $coloane[$j] . "</td>";
					}
					$text .= "<td>" . LANG_Options . "</td>";
				$text .= "</tr>";	
							
				for ($i = 0; $i < $per_pag; $i++) {
					if (!empty($firme[$i]->id_firma)) {
						$text .= "<tr>";
						for ($j = 0; $j < $nr_coloane; $j++) {
							if ($coloane[$j] == 'nume') {
								$text .= "<td><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">" . $firme[$i]->$coloane[$j] . "</a></td>";
							}
							else {
								$text .= "<td>" . $firme[$i]->$coloane[$j] . "</td>";
							}
						}
						$text .= "<td>";
							$text .= "<a href=\"javascript: sterge_firma(" . $firme[$i]->id_firma . ", " . $id_client . ", " . $per_pag . "," . $pagina . ")\"><img border=\"0\" src=\"images/delete.png\" /> " . LANG_Delete . "</a>";				
							$text .= "<a href=\"add_firma.php?id=" . $firme[$i]->id_firma . "\"><img border=\"0\" src=\"images/edit.png\" />" . LANG_Edit . "</a>";				
						$text .= "</td>";	
						
						$text .= "</tr>";	
					}						
				}				
				$text .= "</table>";
				$text .= "<a href=\"add_firma.php\">" . LANG_Add_firma . "</a>";				
			$text .= "</div>";
			
			$text = render_pagini_firma($total, $per_pag, $id_client, $conditie) . $text;
			$arr = array();
			$arr[0] = $text;
			$arr[1] = $total;
			return $arr; 
		}		
	}
	catch (QueryLoadFirmaException $e) {
		return var_dump($e->getMessage());
	}
}


//renders a select combo box
function render_combobox($htmlName, $phpDataValue, $phpDataVisible, $selectedIndex, $disabled = false, $customHtml = "") {
	echo render_combobox_string($htmlName, $phpDataValue, $phpDataVisible, $selectedIndex, $disabled, $customHtml);
}

//renders a select combo box
function render_combobox_string($htmlName, $phpDataValue, $phpDataVisible, $selectedIndex, $disabled = false, $customHtml = "") {
    if ($disabled === TRUE)
        $ret .= '<select name="' . $htmlName . '" id="' . $htmlName . '" disabled="disabled" '.$customHtml.'>';
    else 
        $ret .= '<select name="' . $htmlName . '" id="' . $htmlName . '" '.$customHtml.'>';    
    for ($i = 0; $i < count($phpDataValue); $i++) {
        $selected = '';
        if ($i == $selectedIndex) $selected = ' selected="selected" ';
        $ret .= '<option value="' . $phpDataValue[$i] . '"' . $selected . ">" . $phpDataVisible[$i] . '</option>';
    }
    $ret .= '</select>';
    return $ret;
}

function render_pagini_firma($total, $per_pag, $id_client, $camp = null, $order = null, $pagina_curenta = null, $coloane_firme, $keyword, $tip_firma, $camp_sort) {
	$nr_pagini = ceil($total / $per_pag);
	$text = "";
	$exista_fp = 0;
	$exista_lp = 0;
	
	
	$cols = explode(",", $coloane_firme);
	$nr_cols = count($cols);
	
	$prima_data = 1;
	
	if ($nr_cols == 1) $text_span = '';
	else $text_span = "colspan=\"" . ($nr_cols) . "\"";
	
	// Nu-si are sensul - am comentat linia
    //$conditie = str_replace("'", "@", $conditie);
    
    if ($total > 0) {
		$inceput = "<div style=\"float: left; width: 20%; text-align:left;\" class=\"paginare\"><a onclick=\"javascript: select_all_checkboxes_firms(1); \" style=\"cap_tabel\">" . LANG_Select_all . "</a> / <a onclick=\"javascript: select_all_checkboxes_firms(0); \" style=\"cap_tabel\">" . LANG_Deselect_all . "</a></div>";
        $inceput .= "<div style=\"float: left; width: 60%; text-align:center;\" class=\"paginare\">" . LANG_Pagina;
        for ($i = $pagina_curenta - CT_PAGINARE_INAINTE_DUPA; $i < $pagina_curenta + CT_PAGINARE_INAINTE_DUPA; $i++) {
            if ($i >= 0 && $i < $nr_pagini) {
                
                if ($prima_data == 1) {
                    $fp = $i;
                    $prima_data = 0;
                }
                if ($i != $pagina_curenta) {
                    $text .= ' <a onclick="javascript: arata_firme_pag('. $i . ', '. $per_pag . ", 'content_firme', " . $id_client . ", '" . $keyword . "', '" . $camp . "', '" . $order . "', '" . $camp_sort . "', '" . $tip_firma . "');\">" . ($i+1) . '</a>';    
                }
                else {
                    $text .= ' <a style="font-weight:bold;">' . ($i+1) . "</a>";    
                }
                
                if ($i == 0) {
                    $exista_fp = 1;
                }
                if ($i == ($nr_pagini - 1)) {
                    $exista_lp = 1;
                }
            }
        }    
        $lp = $i;

        if ($fp == 0 || $fp == 1) $text_puncte = "";
        else $text_puncte = " ... ";
        
        if (!$exista_fp) $text = $inceput . ' <a class="cap_tabel" onclick="javascript: arata_firme_pag(0, ' . $per_pag . ", 'content_firme', " . $id_client . ", '" . $keyword . "', '" . $camp . "', '" . $order . "', '" . $camp_sort . "', '" . $tip_firma . "');\">" . LANG_FIRST . "</a> " . $text_puncte . $text;     
        else $text = $inceput . $text;
        
        if ($lp == $nr_pagini || $lp == ($nr_pagini - 1)) $text_puncte = '';
        else $text_puncte = ' ... ';
        
        if (!$exista_lp) $text .= $text_puncte . ' <a class="cap_tabel" onclick="javascript: arata_firme_pag('. $total . ', '. $per_pag . ", 'content_firme', " . $id_client . ", '" . $keyword . "', '" . $camp . "', '" . $order . "', '" . $camp_sort . "', '" . $tip_firma . "');\">" . LANG_LAST . '</a>';     
        $text .= "</div>";
        $text .= "<div style=\"text-align:right; float: right; width: 20%;\">";
            
        $text .= ' ' . LANG_GO_TO . ' <input type="text" id="page_nr" name="page_nr" value="" maxlength="2" size="2" />';
        
        // TODO: conditie e NULL - de ce il folosesti???
        $text .= ' <input onclick="javascript: go_to_page_firme(' . $per_pag . ", 'content_firme', " . $id_client . ", '" . $camp . "', '" . $order . "', " . $nr_pagini . ",'" . $keyword . "');" . '" type="button" value="' . LANG_OK . '" name="go_to_page" id="go_to_page" />';
        
        $text .= "</div>";    
    }
    else {
        $text = "<div style=\"text-align:center;\" class=\"paginare\">" . LANG_Nu_sau_gasit_firme . "</div>";    
    }
	return $text;
}

function render_pagini_comenzi($total, $per_pag, $id_client, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp = null, $order = null, $pagina_curenta = null, $coloane_comenzi, $pret_min=null, $pret_max=null, $cost_min=null, $cost_max=null, $data_scadenta_sol1=null, $data_scadenta_sol2=null, $data_scadenta_exec1=null, $data_scadenta_exec2=null, $data_factura_sol1=null, $data_factura_sol2=null, $data_factura_exec1=null, $data_factura_exec2=null, $sc_incasare=null, $sc_plata=null, $cond_firme=null, $camp_sort = null) {
	
	if ($total > 0) {
		/*
		 * in caz ca sunt date cele 2 valori va trebui sa scot ghilimele de inceput si sfarsit
		 */
		
		$val1 = str_replace("'", "", $val1);
		$val2 = str_replace("'", "", $val2);
		
		$nr_pagini = ceil($total / $per_pag);
		$text = "";

		$exista_fp = 0;
		$exista_lp = 0;
		
		$cols = explode(",", $coloane_comenzi);
		$nr_cols = count($cols);
		
		$prima_data = 1;
		
		if ($nr_cols == 1) $text_span = '';
		else $text_span = "colspan=\"" . ($nr_cols) . "\"";
		$inceput = "<div style=\"float: left; width: 20%; text-align:left;\" class=\"paginare\"><a onclick=\"javascript: selecteaza_toate_checkboxes(1); \" style=\"cap_tabel\">" . LANG_Select_all . "</a> / <a onclick=\"javascript: selecteaza_toate_checkboxes(0); \" style=\"cap_tabel\">" . LANG_Deselect_all . "</a></div>";
		
		$inceput .= "<div style=\"float: left; width: 60%; text-align:center;\" class=\"paginare\">" . LANG_Pagina;
		for ($i = $pagina_curenta - CT_PAGINARE_INAINTE_DUPA; $i < $pagina_curenta + CT_PAGINARE_INAINTE_DUPA; $i++) {
			if ($i >= 0 && $i < $nr_pagini) {
				
				if ($prima_data == 1) {
					$fp = $i;
					$prima_data = 0;
				}
				if ($i != $pagina_curenta) {
                     
					$text .= ' <a onclick="javascript: arata_comenzi_pag('. $i . ', '. $per_pag . ",'pag_and_content'," . $id_client . ",'" . $comanda_incasata . "','" . $comanda_platita . "','" . $scadenta_incasare . "','" . $scadenta_plata . "','" . $f_sol . "','" . $f_exec . "','" . $keyword . "','" . $val1 . "','" . $val2 . "', '" . $camp . "', '" . $order . "', '" . $pret_min . "', '" . $pret_max . "', '" . $cost_min . "', '" . $cost_max . "', '" . $data_scadenta_sol1 . "', '" . $data_scadenta_sol2 . "', '" . $data_scadenta_exec1 . "', '" . $data_scadenta_exec2 . "', '" . $data_factura_sol1 . "', '" . $data_factura_sol2 . "', '" . $data_factura_exec1 . "', '" . $data_factura_exec2 . "', '" . $sc_incasare . "', '" . $sc_plata . "', '" . $cond_firme . "', '" . $camp_sort . "');\">" . ($i+1) . '</a>';	
				}
				else $text .= ' <a style="font-weight:bold;">' . ($i+1) . "</a>";	
				
				if ($i == 0) $exista_fp = 1;
				if ($i == ($nr_pagini - 1)) $exista_lp = 1;

			}
		}	
		$lp = $i;
	
		if ($fp == 0 || $fp == 1) $text_puncte = "";
		else $text_puncte = " ... ";
		
		if (!$exista_fp) $text = $inceput . " <a class=\"cap_tabel\" onclick=\"javascript:   arata_comenzi_pag(0, " . $per_pag . ", 'pag_and_content', " . $id_client . ",'" . $comanda_incasata . "','" . $comanda_platita . "','" . $scadenta_incasare . "','" . $scadenta_plata . "','" . $f_sol . "','" . $f_exec . "','" . $keyword . "','" . $val1 . "','" . $val2 . "', '" . $camp . "', '" . $order . "', '" . $pret_min . "', '" . $pret_max . "', '" . $cost_min . "', '" . $cost_max . "', '" . $data_scadenta_sol1 . "', '" . $data_scadenta_sol2 . "', '" . $data_scadenta_exec1 . "', '" . $data_scadenta_exec2 . "', '" . $data_factura_sol1 . "', '" . $data_factura_sol2 . "', '" . $data_factura_exec1 . "', '" . $data_factura_exec2 . "', '" . $sc_incasare . "', '" . $sc_plata . "', '" . $cond_firme . "', '" . $camp_sort . "');\">" . LANG_FIRST . "</a> " . $text_puncte . $text;	 
		else $text = $inceput . $text;
		
		if ($lp == $nr_pagini || $lp == ($nr_pagini - 1)) $text_puncte = '';
		else $text_puncte = ' ... ';
		
		if (!$exista_lp) $text .= $text_puncte . ' <a class="cap_tabel" onclick="javascript: arata_comenzi_pag(' . ($nr_pagini - 1) . ', ' . $per_pag . ",'pag_and_content'," . $id_client . ",'" . $comanda_incasata . "','" . $comanda_platita . "','" . $scadenta_incasare . "','" . $scadenta_plata . "','" . $f_sol . "','" . $f_exec . "','" . $keyword . "','" . $val1 . "','" . $val2 . "', '" . $camp . "', '" . $order . "', '" . $pret_min . "', '" . $pret_max . "', '" . $cost_min . "', '" . $cost_max . "', '" . $data_scadenta_sol1 . "', '" . $data_scadenta_sol2 . "', '" . $data_scadenta_exec1 . "', '" . $data_scadenta_exec2 . "', '" . $data_factura_sol1 . "', '" . $data_factura_sol2 . "', '" . $data_factura_exec1 . "', '" . $data_factura_exec2 . "', '" . $sc_incasare . "', '" . $sc_plata . "', '" . $cond_firme . "', '" . $camp_sort . "');\">" . LANG_LAST . '</a>';	 
		$text .= "</div>";
		$text .= "<div style=\"text-align:right; float: right; width: 20%;\">";
			
		$text .= ' ' . LANG_GO_TO . ' <input type="text" id="page_nr" name="page_nr" value="" maxlength="2" size="2" />';
		$text .= ' <input onclick="javascript: go_to_page_comenzi(' . $per_pag . ", 'pag_and_content', " . $id_client . ",'" . $comanda_incasata . "','" . $comanda_platita . "','" . $scadenta_incasare . "','" . $scadenta_plata . "','" . $f_sol . "','" . $f_exec . "','" . $keyword . "','" . $val1 . "','" . $val2 . "', '" . $camp . "', '" . $order . "', '" . $nr_pagini . "', '" . $pret_min . "', '" . $pret_max . "', '" . $cost_min . "', '" . $cost_max . "', '" . $data_scadenta_sol1 . "', '" . $data_scadenta_sol2 . "', '" . $data_scadenta_exec1 . "', '" . $data_scadenta_exec2 . "', '" . $data_factura_sol1 . "', '" . $data_factura_sol2 . "', '" . $data_factura_exec1 . "', '" . $data_factura_exec2 . "', '" . $sc_incasare . "', '" . $sc_plata . "', '" . $cond_firme  . "');" . '" type="button" value="' . LANG_OK . '" name="go_to_page" id="go_to_page" />';
		
		$text .= "</div>";
		return $text;	
	}
	else {	
		return "<div style=\"text-align:center;\" class=\"paginare\">" . LANG_Nu_sau_gasit_comenzi . "</div>";
	}
}

function render_firme($db, $tip_firma, $per_pag, $id_client, $pagina, $camp, $order = null, $user, $keyword, $camp_order = null, $val1 = null, $val2 = null) {

	//trebuie obtinut un query si vazut acela cate rezultate returneaza
	
	$arr = array();

	$arr = get_firme($db, $id_client, $pagina, $per_pag, $camp, $order, $user, $keyword, $tip_firma, $camp_order, $val1, $val2);
	
    if (is_array($arr))
	    echo $arr[0];
    else
        return false;
}

function render_comenzi($db, $per_pag, $pagina, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp = null, $order = null, $coloane_comenzi, $pret_min=null, $pret_max=null, $cost_min=null, $cost_max=null, $data_scadenta_sol1=null, $data_scadenta_sol2=null, $data_scadenta_exec1=null, $data_scadenta_exec2=null, $data_factura_sol1=null, $data_factura_sol2=null, $data_factura_exec1=null, $data_factura_exec2=null, $sc_incasare=null, $sc_plata=null, $cond_firme=null, $camp_sort, $currencies = null, $sau_si = null) {
	$arr = array();		        
	$arr = get_comenzi($db, $pagina, $per_pag, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp, $order, $coloane_comenzi, $pret_min, $pret_max, $cost_min, $cost_max, $data_scadenta_sol1, $data_scadenta_sol2, $data_scadenta_exec1, $data_scadenta_exec2, $data_factura_sol1, $data_factura_sol2, $data_factura_exec1, $data_factura_exec2, $sc_incasare, $sc_plata, $cond_firme, $camp_sort, $currencies, $sau_si);

    if (is_array($arr))	echo $arr[0];
    else return false;
    
    return true;
}

function render_firme_search($db, $conditie, $per_pag, $id_client, $pagina) {
	//trebuie obtinut un query si vazut acela cate rezultate returneaza
	
	$arr = array();
	$arr = get_firme_search($db, $id_client, $pagina, $per_pag, $conditie);
	
	
//	render_pagini_firma($arr[1], $per_pag, $id_client, $conditie);
	if (!empty($arr)) echo $arr[0];
	else {
		echo "Nu sunt firme";
	}
	
}

function render_firme_pagini($db, $tip_firma, $per_pag, $id_client) {
	//trebuie obtinut un query si vazut acela cate rezultate returneaza
	
	$conditie = "tip = $tip_firma AND id_client = $id_client";
	$arr = array();
	$arr = get_firme($db, $id_client, 0, $per_pag, $conditie);

    if (is_array($arr))
	    render_pagini_firma($arr[1], $per_pag, $id_client, $conditie);
    else
        return false;
}

function sterge_firma($db, $id_firma, $id_client) {

    try {
	    $gasit = Comanda::getFirmeSolOrExecForComanda($db, $id_firma);	
    }
    catch (QueryGetFirmeSolOrExecForComanda $e) {
        return false;
    }

	if ($gasit == CT_RESULT_OK) {
		echo CT_FIRMA_NU_POATE_FI_STEARSA;
	}
	else {
		echo Firma::queryDeleteById($db, $id_firma, $id_client);
	}
}

function render_filter_and_search_box_firme($id_client, $per_pag) {
	echo '<table align="left" id="wrapper">';
		echo "<thead>";
			echo "<tr>";
				echo "<th colspan=\"6\" align=\"left\">" . LANG_Filtreaza_firme . "</th>";
			echo "</tr>";
		echo "</thead>";
		echo "<tr class=\"capTabel\">";
			echo "<td align=\"right\">" . LANG_Filter_By . "</td>";
			echo "<td>";
				$tip_firma = get_tip_firme();	  	  
	  			echo '<select name="tip_firma" id="tip_firma">';
					echo '<optgroup label="' . LANG_TIP_FIRMA . '" value="text" />';	  	  
					foreach ($tip_firma as $key => $value) {
						if ($value == CT_TIP_FIRMA_ALL)
	    					echo '<option value="' . $value . '" selected="selected">' . $key. '</option>';
	    				else 
	    					echo '<option value="' . $value . '">' . ($key) . '</option>';
	  				}
	  				echo '<optgroup label="' . LANG_Calitate_firma . '" value="text" />';
	  				echo '<option value="cf' . CT_FIRMA_SERIOASA. '">' . LANG_Firma_serioasa . '</option>';
	  				echo '<option value="cf' . CT_FIRMA_NESERIOASA . '">' . LANG_Firma_neserioasa . '</option>';
  				echo '</select>';		
			echo "</td>";

			echo "<td align=\"right\">" . LANG_Search_by . "</td>";
			echo "<td>";
				echo "<span id=\"search_area\">";		
					echo '<input type="text" name="keyword_kk" id="keyword_kk" onkeypress="onEnter(event, \'firme\');" /> ';
				echo "</span>";
				echo "<select onchange=\"javascript: modifica_camp_cautare_firme(this.value)\" name=\"camp_search\" id=\"camp_search\">";	
					echo '<option value="-1">' . LANG_All. '</option>';			
					echo '<option value="nume">' . LANG_NUME. '</option>';			
					echo '<option value="cf">' . LANG_CF. '</option>';			
					echo '<option value="rc">' . LANG_RC. '</option>';			
					echo '<option value="tel_fix">' . LANG_TEL_FIX. '</option>';			
					echo '<option value="tel_fax">' . LANG_TEL_FAX. '</option>';			
					echo '<option value="tel_mobil">' . LANG_TEL_MOBIL. '</option>';			
					echo '<option value="email">' . LANG_EMAIL. '</option>';			
					echo '<option value="web">' . LANG_WEB. '</option>';		
					echo '<option value="1rute">' . LANG_Rute. '</option>';		
				echo "</select>";
			echo "</td>";

			echo "<td align=\"right\">" . LANG_Per_Page . "</td>";
			echo "<td>";
				echo "<select name=\"per_page\" id=\"per_page\">";
					if (10 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
					echo "<option value=\"10\"$text>10</option>";
					if (20 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
					echo "<option value=\"20\"$text>20</option>";
					if (30 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
					echo "<option value=\"30\"$text>30</option>";
					if (40 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
					echo "<option value=\"40\"$text>40</option>";
					if (50 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
					echo "<option value=\"50\"$text>50</option>";
				echo "</select>";	
				echo " <input onclick=\"javascript: show_firme('content_firme', " . 0 . ");\" type=\"button\" name=\"filtreaza\" value=\"" . LANG_Show_firme . "\" />";
			echo "</td>";
		echo "</tr>";
	echo '</table>';	
}

function render_filter_and_search_box_comanda($db, $id_client, $per_pag) {
	echo '<div align="left">';		
		echo "<table id=\"wrapper\">";	
			echo "<thead>";	
				echo "<tr>";
					echo "<th>" . LANG_Filter_By . "</th>"; 
					echo "<th>" . LANG_Comanda_incasata . "</th>"; 
					echo "<th>" . LANG_Comanda_platita . "</th>"; 
					echo "<th>" . LANG_Scadenta_incasare_sapt . "</th>"; 
					echo "<th>" . LANG_Scadenta_plata_sapt . "</th>"; 
					echo "<th>" . LANG_Firma_solicitant . "</th>"; 
					echo "<th></th>"; 
					echo "<th>" . LANG_Firma_executant . "</th>"; 
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td>";
					echo "<input type=\"button\" onclick=\"javascript: arata_modal_cautare_avansata_comenzi(" . $id_client . ");\" value=\"" . LANG_Cautare_avansata . "\" />";
				echo "</td>";
				echo "<td>";
					echo '<select name="incasata" id="incasata_sel">';
						echo "<option value=\"-1\"> --- </option>"; 
						echo "<option value=\"" . CT_COMANDA_INCASATA ."\">" . LANG_Da . "</option>"; 
						echo "<option value=\"" . CT_COMANDA_NEINCASATA ."\">" . LANG_Nu . "</option>"; 
						echo "<option value=\"" . CT_COMANDA_INCASATA_PARTIAL ."\">" . LANG_Partial . "</option>"; 
					echo "</select>";		
				echo "</td>";
				echo "<td>";
					echo '<select name="platita" id="platita_sel">';
						echo "<option value=\"-1\"> --- </option>"; 
						echo "<option value=\"" . CT_COMANDA_PLATITA ."\">" . LANG_Da . "</option>"; 
						echo "<option value=\"" . CT_COMANDA_NEPLATITA ."\">" . LANG_Nu . "</option>"; 
						echo "<option value=\"" . CT_COMANDA_PLATITA_PARTIAL ."\">" . LANG_Partial . "</option>"; 
					echo "</select>";						
				echo "</td>";				
				echo "<td>";
					echo '<select name="sc_incasare" id="sc_incasare_sel">';
						echo "<option value=\"-1\"> --- </option>"; 
						echo "<option value=\"1\">1 " . LANG_saptamana . "</option>"; 
						echo "<option value=\"2\">2 " . LANG_saptamani . "</option>"; 
						echo "<option value=\"3\">3 " . LANG_saptamani . "</option>"; 
						echo "<option value=\"4\">4 " . LANG_saptamani . "</option>"; 
					echo "</select>";				
				echo "</td>";	
				echo "<td>";			
					echo '<select name="sc_plata" id="sc_plata_sel">';
						echo "<option value=\"-1\"> --- </option>"; 
						echo "<option value=\"1\">1 " . LANG_saptamana . "</option>"; 
						echo "<option value=\"2\">2 " . LANG_saptamani . "</option>"; 
						echo "<option value=\"3\">3 " . LANG_saptamani . "</option>"; 
						echo "<option value=\"4\">4 " . LANG_saptamani . "</option>"; 
					echo "</select>";				
				echo "</td>";							
				echo "<td>";
					echo '<select name="f_sol_sel" id="f_sol_sel" onchange="javascript: check_f_sol(0);">';
						echo "<option value=\"-1\"> --- </option>"; 
						$firme = array();
						$firme = Firma::queryLoadByClient($db, $id_client);
						$total = count($firme);
						for ($i = 0; $i < $total; $i++) {
							echo "<option value=\"" . $firme[$i]->id_firma . "\">" . $firme[$i]->nume . "</option>";
						}			
					echo "</select>";				
				echo "</td>";
				echo "<td>";
					echo '<select name="sau_si" id="sau_si" onchange="javascript: check_f_sol(1);">';
						echo "<option value=\"-1\"> --- </option>"; 
						echo "<option value=\"OR\">" . LANG_OR . "</option>"; 
						echo "<option value=\"AND\">" . LANG_AND . "</option>"; 
					echo "</select>";				
				echo "</td>";		
				echo "<td>";		
					echo '<select name="f_exec_sel" id="f_exec_sel" onchange="javascript: check_f_sol(2);">';
						echo "<option value=\"-1\"> --- </option>"; 
						for ($i = 0; $i < $total; $i++) {
							echo "<option value=\"" . $firme[$i]->id_firma . "\">" . $firme[$i]->nume . "</option>";
						}			
					echo "</select>";				
				echo "</td>";		
			echo "</tr>";			
			echo "<tr class=\"capTabel\">";			
				echo "<td>" . LANG_Search . "</td>";
				echo "<td colspan=\"6\" align=\"left\">";
					
					echo " <span id=\"campuri\"><input onkeypress=\"onEnter(event, 'comenzi')\" type=\"text\" id=\"keyword\" name=\"keyword\" value=\"\" /></span>";
					echo " " . LANG_in . " ";
					echo " <select name=\"camp_sel\" id=\"camp_sel\" onchange=\"javascript: modifica_camp(this.value, 'cautare_simpla');\">";
						echo '<optgroup label="' . LANG_Campuri_comanda . '" value="text" />';
                        echo "<option value=\"-1\">" . LANG_All . "</option>";
						echo "<option value=\"nr_comanda_sol\">" . LANG_Nr_comanda_sol . "</option>";
						echo "<option value=\"nr_comanda_exec\">" . LANG_Nr_comanda_exec . "</option>";
						echo "<option value=\"1incarcare_descarcare\">" . LANG_Loc_incarcare_descarcare . "</option>";
						echo "<option value=\"nr_factura_sol\">" . LANG_nr_factura_sol . "</option>";
						echo "<option value=\"nr_factura_exec\">" . LANG_nr_factura_exec . "</option>";
						echo "<option value=\"nume_sofer\">" . LANG_Nume_sofer . "</option>";
						echo "<option value=\"tel_sofer\">" . LANG_tel_sofer . "</option>";
						echo "<option value=\"nr_inmatriculare\">" . LANG_nr_inmatriculare . "</option>";
						echo "<option value=\"fel_camion\">" . LANG_Fel_camion . "</option>";
						
						echo '<optgroup label="' . LANG_DATE_COMANDA . '" value="text" />';
						echo "<option value=\"1data_incarcare\">" . LANG_data_incarcarii . "</option>";
						echo "<option value=\"1data_descarcare\">" . LANG_Data_descarcarii . "</option>";
						echo "<option value=\"1data_scadenta_sol\">" . LANG_Data_scadenta_sol . "</option>";
						echo "<option value=\"1data_scadenta_exec\">" . LANG_Data_scadenta_exec . "</option>";						
						echo "<option value=\"1data_factura_sol\">" . LANG_Data_factura_sol . "</option>";												
						echo "<option value=\"1data_factura_exec\">" . LANG_Data_factura_exec . "</option>";
						
					echo "</select>";
					echo " " . LANG_Per_Page . " ";
					echo "<select name=\"per_page\" id=\"per_page\">";
                        if (10 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
                        echo "<option value=\"10\"$text>10</option>";
                        if (20 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
                        echo "<option value=\"20\"$text>20</option>";
                        if (30 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
                        echo "<option value=\"30\"$text>30</option>";
                        if (40 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
                        echo "<option value=\"40\"$text>40</option>";
                        if (50 == $per_pag) $text = " selected=\"selected\" "; else $text = "";
                        echo "<option value=\"50\"$text>50</option>";
					echo "</select>";	
					echo " <input onclick=\"javascript: show_comenzi('pag_and_content', " . 0 . ");\" type=\"button\" name=\"filtreaza\" value=\"" . LANG_Cauta . "\" />";
				echo "</td>";
				echo "<td align=\"right\">";										

				echo "</td>";				
		echo "</table>";						
	echo '</div>';	
}

function render_users_table($users) {
	echo '<table border="0" cellspacing="0" id="wrapper">';
		echo "<thead>";
			echo "<tr>";
				echo "<th align=\"center\" colspan=\"7\">" . LANG_Current_users . "</th>";
			echo "</tr>";
		echo "</thead>";
		echo '<tr class="capTabel">';
			echo '<td><b>'.LANG_NR_CRT.'</b></td>';
			echo '<td><b>'.LANG_Username.'</b></td>';
			echo '<td><b>'.LANG_NUME.'</b></td>';
			echo '<td><b>'.LANG_PRENUME.'</b></td>';			
			echo '<td colspan="3"><b>'.LANG_EMAIL.'</b></td>';			
		echo '</tr>';
		
		$j = 0;
		if (count($users)) {
			for ($i = 0; $i < count($users); $i++) {
				if ($users[$i]->deleted != CT_DELETED) {
					$j++;
					echo '<tr onmouseout=this.className="whiteThing" onmouseover=this.className="blueThing" class="whiteThing">';
						echo "<td>$j</td>";
						echo '<td>'.$users[$i]->username."</td>";
						echo '<td>'.$users[$i]->nume."</td>";
						echo '<td>'.$users[$i]->prenume."</td>";
						echo '<td>'.$users[$i]->email."</td>";
						
						//transmit $i ca sa stiu ca al i-lea contact din array se va modifica/sterge
						
						echo '<td><input type="button" name="edit" name="edit" value="'.LANG_EDIT.'" onclick="javascript: edit_user(' . $i . ');" /></td>';
						echo '<td><input type="button" name="delete" id="delete" value="'.LANG_DELETE.'" onclick="javascript: sterge_user('.$i.');" /></td>';
					echo '</tr>';
				}
			}
		}
		else {
			echo "<tr>";
				echo "<td colspan=\"7\" align=\"center\">" . LANG_Nu_exista_nici_un_utilizator_adaugat . "</td>";
			echo "</tr>";
		}
	echo '</table>';
	echo '<input type="hidden" name="user_number" id="user_number" value="'.$j.'"/>';
}

function create_user_folders($user_id) {
	/*
	 * urmeaza sa creez structura pe hard a directoarelor pentru printari si alte chestii
	 * prima data creez un folder cu numele = id-ul userului nou creat
	 */
	
	$last_line = system("mkdir " . USERS_PATH . "$user_id > /dev/null", $ret_val);
	
	/*
	 * apoi creez folderele pentru fiecare tiparire in parte
	 */
				
	$last_line = system("mkdir " . USERS_PATH . "$user_id/comanda_dez > /dev/null", $ret_val);
	$last_line = system("mkdir " . USERS_PATH . "$user_id/firma_dez > /dev/null", $ret_val);
	$last_line = system("mkdir " . USERS_PATH . "$user_id/contract_dez > /dev/null", $ret_val);
	$last_line = system("mkdir " . USERS_PATH . "$user_id/factura_dez > /dev/null", $ret_val);
	$last_line = system("mkdir " . USERS_PATH . "$user_id/factura_client_dez > /dev/null", $ret_val);			
	
	/*
	 * acuma voi copia din printTemplates acele foldere cu tot cu continut
	 */
	
	system("cp -R " . ODT_TEMPLATES_PATH . "comanda/* " . USERS_PATH . "$user_id/comanda_dez/ > /dev/null", $ret_val);
	system("cp -R " . ODT_TEMPLATES_PATH . "firma/* " . USERS_PATH . "$user_id/firma_dez/ > /dev/null", $ret_val);
	system("cp -R " . ODT_TEMPLATES_PATH . "contract/* " . USERS_PATH . "$user_id/contract_dez/ > /dev/null", $ret_val);
	system("cp -R " . ODT_TEMPLATES_PATH . "factura/* " . USERS_PATH . "$user_id/factura_dez/ > /dev/null", $ret_val);			
	system("cp -R " . ODT_TEMPLATES_PATH . "factura_client/* " . USERS_PATH . "$user_id/factura_client_dez/ > /dev/null", $ret_val);

	/*
	 * pun si drepturi de scriere
	 */
	
	$last_line = system("chmod 0777 -R " . USERS_PATH . "$user_id/ > /dev/null", $ret_val);
}
                          
function create_new_user($db, $id_client, $username, $nume, $prenume, $email, $tip, $optiune, $index) {
	// TODO: de trimis email-uri
	session_start();
	if ($optiune == "insert") {
		//Backup	
		$username_bkp = $_SESSION['users'][$index]->username;
		$email_bkp = $_SESSION['users'][$index]->email;
		
		try {
			$pass = createRandomPassword();
			$user = new User($id_client, $username, $pass, $tip, $email, '0', CT_MUST_CHANGE_PASSWORD);	
						
            $user->nume = $nume;
            $user->prenume = $prenume;
			
			$user_id = $user->queryInsert($db);
			array_push($_SESSION['users'], $user);	

			create_user_folders($user_id);											
		}
		catch (QueryInsertUserException $e) {
			//Rolback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return false;
		}
		catch (QueryDuplicateUsernameUserException $e) {
			//Rolback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return CT_DUPLICATE_USERNAME;
		}
		catch (QueryDuplicateEmailUserException $e) {
			//Rolback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return CT_DUPLICATE_EMAIL;
		}
	}
	
	if ($optiune == "update") {	
		//Backup
		$username_bkp = $_SESSION['users'][$index]->username;
		$email_bkp = $_SESSION['users'][$index]->email;

		try {				
			$_SESSION['users'][$index]->username = $username;		
			$_SESSION['users'][$index]->nume = $nume;		
			$_SESSION['users'][$index]->prenume = $prenume;		
			$_SESSION['users'][$index]->email = $email;		
			$_SESSION['users'][$index]->tip = $tip;		
			
			$_SESSION['users'][$index]->queryLightUpdate($db);
			notice_msg(LANG_User_edited_successfully);
		}
		catch (QueryUpdateUserException $e) {
			// Rollback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return false;
		}
		catch (QueryWrongVersionException $e) {
			// Rollback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return false;
		}
		catch (QueryDuplicateUsernameUserException $e) {
			// Rollback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return CT_DUPLICATE_USERNAME;
		}
		catch (QueryDuplicateEmailUserException $e) {
			// Rollback
			$_SESSION['users'][$index]->username = $username_bkp;
			$_SESSION['users'][$index]->email = $email_bkp;
			return CT_DUPLICATE_EMAIL;
		}
	}
    
    return true;
}

function sterge_user($db, $index) {	
	try {
        $_SESSION['users'][$index]->queryDelete($db);	
        
        /*
         * trebuie sterse de asemnea intreaga structura de foldere a userului
         */
        $user = $_SESSION['users'][$index];
        $user_id = $user->id_user;
		$last_line = system("rm -R " . USERS_PATH . "$user_id > /dev/null", $ret_val);
    }
    catch (QueryDeleteUserException $e) {
        return false;
    }
    
	$_SESSION['users'][$index]->deleted = CT_DELETED;
    
    return true;
}

function sterge_and_render_comenzi($db, $id_comanda, $id_client, $per_pag, $pagina, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp = null, $order = null, $coloane_comenzi, $pret_min=null, $pret_max=null, $cost_min=null, $cost_max=null, $data_scadenta_sol1=null, $data_scadenta_sol2=null, $data_scadenta_exec1=null, $data_scadenta_exec2=null, $data_factura_sol1=null, $data_factura_sol2=null, $data_factura_exec1=null, $data_factura_exec2=null, $sc_incasare=null, $sc_plata=null, $cond_firme=null, $camp_sort) {
	try {
        Comanda::queryDeleteById($db, $id_comanda);
    }
    catch (QueryDeleteComandaException $e) {
        return false;
    }
    
	return render_comenzi($db, $per_pag, $pagina, $comanda_incasata, $comanda_platita, $scadenta_incasare, $scadenta_plata, $f_sol, $f_exec, $keyword, $val1, $val2, $camp, $order, $coloane_comenzi, $pret_min, $pret_max, $cost_min, $cost_max, $data_scadenta_sol1, $data_scadenta_sol2, $data_scadenta_exec1, $data_scadenta_exec2, $data_factura_sol1, $data_factura_sol2, $data_factura_exec1, $data_factura_exec2, $sc_incasare, $sc_plata, $cond_firme, $camp_sort);
}

function render_checkbox_act_necesar($comanda, $nume_camp, $label, $nume_aditional = null) {
	$nume_camp2 = $nume_camp.'2';
	if ($comanda->$nume_camp == CT_ACT_NECESAR_SI_EXISTENT || $comanda->$nume_camp == CT_ACT_NECESAR_SI_NEEXISTENT) { 
		$option = ' checked="checked"';
	}
	else $option = "";
 	echo '<input type="checkbox" value="1" name="'.$nume_camp.'" id="'.$nume_camp.'" '.$option.'/>';
	echo '<label for="'.$nume_camp.'">'.$label.'</label>';
}

function render_checkbox_act_trimis($comanda, $nume_camp, $label) {
	$nume_camp2 = $nume_camp.'2';
	if ($comanda->$nume_camp == CT_ACT_NECESAR_SI_EXISTENT || $comanda->$nume_camp == CT_ACT_NENECESAR_SI_EXISTENT) { 
		$option = ' checked="checked"';
	}
	else $option = "";
	echo '<input type="checkbox" value="1" name="'.$nume_camp2.'" id="'.$nume_camp2.'" '.$option.' />';
	echo '<label for="'.$nume_camp2.'">'.$label.'</label>';
}

function render_date_field_button($dataActuala, $numeCamp, $numeDiv, $onChange = null, $enabled = null, $xid = null, $calid = null, $read_only = null, $ora = false, $withDelete = true) {
    if ($dataActuala != null)
        $initialValue = getDateForUser($dataActuala, $ora); //date("d-m-Y", strtotime($dataActuala));
    else
        $initialValue = '';
    if ($onChange != null)
        $change = $onChange;
    $text = '';
    
    if ($enabled == 1) {
         $tx = " disabled ";
         //$tx2 = "";
    }
    else $tx = "";             
    
    //if ($read_only == 1) $ro = "";
    //else $read_only = " readonly=\"readonly\" "; 
     
    $format_ora = '';
    $clasa_input_date = 'input_date';
    if ($ora == true) {
        $format_ora = ' hh:ii';
        $clasa_input_date = 'input_date_mare';
    }
 
    $text .= '<input type="text" ' . $tx . ' readonly="readonly" class="'.$clasa_input_date.'" value="'.$initialValue.'"' . ' name="'.$numeCamp.'" id="'.$numeCamp.'" />';
    $text .= '&nbsp;<input id="' . $calid . '" ' . $tx . ' type="image" src="'.IMG_PATH.'calendar3.gif" alt="'.LANG_select_date.'" ';
   
        $text .= 'onclick="displayCalendar(document.getElementById(\''.$numeCamp.'\'),\'dd'.CT_DATE_SEPARATOR.'mm'.CT_DATE_SEPARATOR.'yyyy'.$format_ora.'\',this,true,\''.$numeDiv.'\', \''.$onChange.'\');return false" ';
    $text .= ' />';
    
    if ($withDelete) {
        $text .= '<input ' . $tx . ' type="image" src="' . IMG_PATH . 'deleteButton.gif" id="' . $xid . '"';
        $text .= ' onClick="document.getElementById(\''.$numeCamp.'\').value=\'\'; return false;" />';
    }
    return $text;
}

function render_date_field_with_ora_button($dataActuala, $numeCamp, $numeDiv, $onChange = null, $enabled = null, $xid = null, $calid = null, $read_only = null) {
    
    return render_date_field_button($dataActuala, $numeCamp, $numeDiv, $onChange, $enabled, $xid, $calid, $read_only, true);
}

function check_field($id) {
	global $wrong_ids;
	if (isset($wrong_ids[$id])) echo 'class="incorrect"';
}

function render_dashboard($tip, $id_client) {
	require_once('paths.inc');
    require_once(DB_PATH.'db.inc');
	global $currencies;
	
	$db = db_connect();

	if ($tip == CT_DASHBOARD_MARFA) $titlu_tabel = LANG_Marfuri;
	if ($tip == CT_DASHBOARD_CAMION) $titlu_tabel = LANG_Camioane;
	
	try {
		$arrDashboard = Dashboard::getActivity($db, $id_client, $tip);
			
		echo "<table id=\"wrapper\" width=\"100%\">";	
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"12\" align=\"center\">" . $titlu_tabel . "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"center\"><b>" . LANG_Added_by . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Adaugat_in . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Tara_plecare . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Oras_plecare . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Data_plecare . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Tara_sosire . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Oras_sosire . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Data_sosire . "</b></td>";	
				echo "<td align=\"center\"><b>" . LANG_Pret . "</b></td>";							
				echo "<td align=\"center\"><b>" . LANG_Kilometrii . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Comentariu . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Optiuni . "</b></td>";
			echo "</tr>";
			
			if (count($arrDashboard) > 0) {
	     		foreach ($arrDashboard as $dash) {
	          			echo "<tr onmouseout=this.className=\"blueThing\" onmouseover=this.className=\"whiteThing\" class=\"blueThing\">";
							echo "<td align=\"center\">" . $dash->nume_user . " " . $dash->prenume_user . "</td>";
	          				echo "<td align=\"center\">" . getDateForUser($dash->date_added, true) . "</td>";	          		
	          				echo "<td align=\"center\">" . $dash->tara_plecare . "</td>";
	          				echo "<td align=\"center\">" . $dash->oras_plecare . "</td>";
	          				echo "<td align=\"center\">" . getDateForUser($dash->data_plecare, true) . "</td>";
	          				echo "<td align=\"center\">" . $dash->tara_sosire . "</td>";
	          				echo "<td align=\"center\">" . $dash->oras_sosire . "</td>";
	          				echo "<td align=\"center\">" . getDateForUser($dash->data_sosire, true) . "</td>";	          				
	          				echo "<td align=\"center\">" . prepareFloatForUser($dash->pret_total) . " " . $currencies[$dash->moneda]. "</td>";	          				
	          				echo "<td align=\"center\">" . prepareFloatForUser($dash->km) . "</td>";	          				
	          				echo "<td align=\"center\">" . $dash->comentariu . "</td>";
	          				echo "<td align=\"center\">";
	          					echo "<button onclick=\"javascript: delete_dash($dash->dashboard_id, $tip);\" \" id=\"delete_dash" . $dash->dashboard_id . "\"><img src=\"" . IMG_PATH . "delete.png\" /></button>";
	          					echo "<button onclick=\"javascript: show_modal_add_dashboard($tip, $dash->dashboard_id);\" id=\"edit_dash" . $dash->dashboard_id . "\"><img src=\"" . IMG_PATH . "edit.png\" /></button>";
	          					echo "<button onclick=\"javascript: dash_to_order($dash->dashboard_id);\" id=\"in_comanda_dash" . $dash->dashboard_id . "\"><img src=\"" . IMG_PATH . "to_order.png\" /> " . LANG_In_Comanda . "</button>";
	          				echo "</td>";
	          			echo "</tr>";	          		         
	     		}	     
			}
			else {
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"12\" align=\"center\">";
	     				echo LANG_Nu_exista_inregistrari_in_dashboard;
	     			echo "</td>";
	     		echo "</tr>";		     
			}
			
     		echo "<tr class=\"capTabel\">";	
     			echo "<td colspan=\"12\" align=\"left\">";
                    if ($tip == CT_DASHBOARD_MARFA)
                        $titlu_buton = LANG_Add_marfuri;
                    else
                        $titlu_buton = LANG_Add_camioane;
					echo "<input onclick=\"javascript: show_modal_add_dashboard($tip, -1); \" type=\"button\" value=\"" . $titlu_buton . "\" id=\"id_dashboad\" />";
     			echo "</td>";
     		echo "</tr>";					
		echo "</table>";
	}
	catch (QueryLoadDashboardException $e) {
		redirectOnError(CT_LOAD_LAST_N_FIRME);
	}	
}

function render_last_firms($id_client) {
	
	require_once('paths.inc');
	require_once(DB_PATH.'db.inc');
	$db = db_connect();
	$firme = array();	
	
	try {
		$firme = Firma::getLast($db, $id_client, CT_MAX_SHOW_FIRME);
			
		echo "<table id=\"wrapper\">";	
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"4\" align=\"center\">" . LANG_Last_firms_added . "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"center\"><b>" . LANG_Nume_firma . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_TEL_FIX . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_TEL_FAX . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_TEL_MOBIL . "</b></td>";
			echo "</tr>";
			
			if (count($firme) > 0) {
	     		for ($i = 0; $i < CT_MAX_SHOW_FIRME; $i++) {
	     		    if (!empty($firme[$i])) {
	          			echo "<tr onmouseout=this.className=\"blueThing\" onmouseover=this.className=\"whiteThing\" class=\"blueThing\">";
	          				echo "<td align=\"center\"><a href=\"view_firma.php?id=" . $firme[$i]->id_firma . "\">" . $firme[$i]->nume . "</a></td>";
	          				echo "<td align=\"center\">" . $firme[$i]->tel_fix . "</td>";
	          				echo "<td align=\"center\">" . $firme[$i]->tel_fax . "</td>";
	          				echo "<td align=\"center\">" . $firme[$i]->tel_mobil . "</td>";
	          			echo "</tr>";	          		         
	     		    }
	     		}
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"4\" align=\"right\">";
	     				echo "<input type=\"button\" onclick=\"javascript: multe_firme('comenzi_neplatite', 1);\" value=\"" . LANG_More . "\" />";
	     			echo "</td>";
	     		echo "</tr>";		     
			}
			else {
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"4\" align=\"center\">";
	     				echo LANG_Nu_exista_inca_firme_adaugate;
	     			echo "</td>";
	     		echo "</tr>";		     
			}
				
		echo "</table>";
	}
	catch (QueryLoadFirmaException $e) {
		redirectOnError(CT_LOAD_LAST_N_FIRME);
	}
}
	/*
	 * 
	 */
function timeleft($begin, $end, $echoYES_NO) {
	
	$dif = $end - $begin;
	
	//$years=intval($dif/(60*60*24*365));
//	$dif=$dif-($years*(60*60*24*365));
//	
//	$months=intval($dif/(60*60*24*30));
//	$dif=$dif-($months*(60*60*24*30));
//	
//	$weeks=intval($dif/(60*60*24*7));
//	$dif=$dif-($weeks*(60*60*24*7));
	
	$days=intval($dif/(60*60*24));
	$dif=$dif-($days*(60*60*24));
	
	$hours=intval($dif/(60*60));
	$dif=$dif-($hours*(60*60));
	
	$minutes=intval($dif/(60));
	$seconds=$dif-($minutes*60);
	
	$s='';
	
	if (abs($days) > 0)
        $s.= $days." " . LANG_zile;
    else
	    if (abs($hours) > 0) 
            $s.= $hours." " . LANG_ore;
        else
	        if (abs($minutes) > 0) 
                $s.= $minutes." " . LANG_minute;
	
	if ($echoYES_NO) echo $s;
	
//    return $days + (7 * $weeks) + (30 * $months);
	return $days;
} 
	
function render_comenzi_incarcare_descarcare_urgente($id_client, $intHowMany, $incarcare_descarcare, $id_lista) {
	require_once('paths.inc');
	require_once(DB_PATH.'db.inc');
	
	$db = db_connect();
	$adrese = array();	
	
	try {
        $tip_adresa = $incarcare_descarcare;
		
        $adrese = Comanda::getLast_incarcari($db, $id_client, $intHowMany, $incarcare_descarcare);

		$setari_client = SetariClient::queryLoadSetariClient($db, $id_client);
//		var_dump($adrese);
		echo "<table id=\"wrapper\">";
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"11\" align=\"center\">";
					if ($incarcare_descarcare == CT_ADRESA_COMANDA_INCARCARE)
						echo LANG_Comenzi_to_incarcat;
					else
						echo LANG_Comenzi_to_descarcat;
					echo "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"center\"><b>" . LANG_DATA . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Timp_ramas . "</b></td>";			
				echo "<td align=\"center\"><b>" . LANG_ADRESA . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_ORAS . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_JUDET . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_TARA . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Tip_marfa . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_comanda_exec . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_comanda_sol . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_referinta_sol . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Options . "</b></b></td>";
			echo "</tr>";
			
			if ($incarcare_descarcare == CT_ADRESA_COMANDA_INCARCARE)
				$camp = 'zile_alarma_incarcari';
			else
				$camp = 'zile_alarma_descarcari';
//			var_dump($setari_client->$camp);	
			if (count($adrese) > 0) {
				for ($i = 0; $i < count($adrese); $i++) {
					$ramas = timeleft($adrese[$i]['finish'], $adrese[$i]['start'], 0);
	     			if ($ramas <= $setari_client->$camp) {
	     				$bg_color = " class=\"redThing\" onmouseout=this.className=\"redThing\" onmouseover=this.className=\"blueThing\"";
	     			}
	     			else $bg_color = " class=\"blueThing\" onmouseout=this.className=\"blueThing\" onmouseover=this.className=\"whiteThing\"";
	     			echo "<tr $bg_color>";
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->data . "</td>";
	     				echo "<td align=\"center\">";
	     					timeleft($adrese[$i]['finish'], $adrese[$i]['start'], 1);
	     				echo "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->adresa . "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->oras . "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->judet . "</td>";	
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->tara . "</td>";			
	     				echo "<td align=\"center\">" . $adrese[$i]['adresa']->tip_marfa . "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['nr_comanda_exec'] . "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['nr_comanda_sol'] . "</td>";
	     				echo "<td align=\"center\">" . $adrese[$i]['nr_referinta_sol'] . "</td>";
	     				echo "<td align=\"center\">";
                        // TODO: OPTIMIZARE, TATA
                        echo "<button onclick=\"javascript: document.location='add_comanda.php?id=".$adrese[$i]['id_comanda']."';\" id=\"in_comanda_dash" . $dash->dashboard_id . "\">" . LANG_View_Comanda . "</button>";
                        echo '<input type="button" onclick="javascript: show_modal_confirma_incarcare_descarcare('.$adrese[$i]['adresa']->id_adresa.', '.$adrese[$i]['id_comanda'].', '.$tip_adresa.', \''.$id_lista .'\');" value="'. LANG_Detalii_Confirma .'" />';
	     				echo "</td>";
	     			echo "</tr>";		
	     		}     			
			}	     		     
			else {
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"5\" align=\"center\">";
	     				if ($incarcare_descarcare == CT_ADRESA_COMANDA_INCARCARE)
	     					echo LANG_Nu_exista_comenzi_ptr_incarcat;
	     				else
	     					echo LANG_Nu_exista_comenzi_ptr_descarcat;
	     			echo "</td>";
	     		echo "</tr>";	     		    		     		     
			}
			
		echo "</table>";
	}
	catch (QueryLoadComandaException $e) {
		redirectOnError(CT_GET_LAST_INCASARI);				
	}
	catch (QueryLoadSetariException $e) {
		redirectOnError(CT_LOAD_SETARI);
	}
	catch (QuerySettingsNotExistException $e) {
		redirectOnError(CT_SETTINGS_NOT_EXIST);
	}
    catch (QueryLoadFirmaException $e) {
    	redirectOnError(CT_LOAD_FIRMA_BY_ID);
	}
}

function render_incasari_urgente($id_client, $intHowMany) {
	require_once('paths.inc');
	require_once(DB_PATH.'db.inc');
	
	$db = db_connect();
	$comenzi = array();	
	
	try {
		$com_zile = Comanda::getLast_incasari($db, $id_client, $intHowMany);
		$comenzi = $com_zile[0];
		$nr_zile_dif = $com_zile[1];
		
		$setari_client = SetariClient::queryLoadSetariClient($db, $id_client);
		
		echo "<table id=\"wrapper\" width=\"600\">";
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"5\" align=\"center\">" . LANG_Comenzi_to_incasat . "</td>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"center\"><b>" . LANG_Firma_solicitant . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_comanda_sol . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Data_scadenta_sol . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_zile_ramase . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Options . "</b></b></td>";
			echo "</tr>";
			if (count($comenzi) > 0) {
	     		for ($i = 0; $i < count($comenzi); $i++) {
	     			if ($nr_zile_dif[$i] <= $setari_client->zile_alarma_incasari) {
	     				$bg_color = " class=\"redThing\" onmouseout=this.className=\"redThing\" onmouseover=this.className=\"blueThing\"";
	     			}
	     			else $bg_color = " class=\"whiteThing\" onmouseout=this.className=\"whiteThing\" onmouseover=this.className=\"blueThing\"";
	     			echo "<tr $bg_color>";
     					$firma = Firma::queryLoadById($db, $comenzi[$i]->id_firma_sol, $id_client);
	     				echo "<td align=\"center\"><a href=\"view_firma.php?id=" . $firma->id_firma . "\">" . $firma->nume . "</a></td>";
	     				echo "<td align=\"center\">" . $comenzi[$i]->nr_comanda_sol . "</td>";
	     				echo "<td align=\"center\">" . getDateForUser($comenzi[$i]->data_scadenta_sol) . "</td>";
	     				echo "<td align=\"center\">" . $nr_zile_dif[$i] . "</td>";				
	     				echo "<td align=\"center\">";
	     					echo "<input type=\"button\" onclick=\"javascript: fa_plata_incasare(0, " . $comenzi[$i]->id_comanda . ");\" value=\"" . LANG_Do_incasare . "\" />";	
	     				echo "</td>";
	     			echo "</tr>";	
	     		}
	     		
	     		$_SESSION['camp_comenzi'] = "data_scadenta_sol"; 
	     		$_SESSION['order_comenzi'] = "DESC";
	     		
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"5\" align=\"right\">";
	     				echo "<input type=\"button\" onclick=\"javascript: multe_comenzi('comenzi_neincasate',1);\" value=\"" . LANG_More . "\" />";	
	     			echo "</td>";
	     		echo "</tr>";	     		     
			}
			else {
	     		echo "<tr class=\"capTabel\">";	
	     			echo "<td colspan=\"5\" align=\"center\">";
	     				echo LANG_Nu_exista_comenzi_ptr_incasat;	
	     			echo "</td>";
	     		echo "</tr>";	     		    		     		     
			}
			
		echo "</table>";
	}
	catch (QueryLoadComandaException $e) {
		redirectOnError(CT_GET_LAST_INCASARI);				
	}
	catch (QueryLoadSetariException $e) {
		redirectOnError(CT_LOAD_SETARI);
	}
	catch (QuerySettingsNotExistException $e) {
		redirectOnError(CT_SETTINGS_NOT_EXIST);
	}
    catch (QueryLoadFirmaException $e) {
    	redirectOnError(CT_LOAD_FIRMA_BY_ID);
	}
}

function render_plati_urgente($id_client, $intHowMany) {
	require_once('paths.inc');
	require_once(DB_PATH.'db.inc');
	
	$db = db_connect();
	$comenzi = array();	
	
	try {
		$setari_client = SetariClient::queryLoadSetariClient($db, $id_client);
			
		$com_zile = Comanda::getLast_plati($db, $id_client, $intHowMany);
		$comenzi = $com_zile[0];
		$nr_zile_dif = $com_zile[1];
		echo "<table id=\"wrapper\" width=\"600\">";
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"5\" align=\"center\">" . LANG_Comenzi_to_platit . "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"center\"><b>" . LANG_Firma_solicitant . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_comanda_sol . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Data_scadenta_exec . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Nr_zile_ramase . "</b></td>";
				echo "<td align=\"center\"><b>" . LANG_Options . "</b></td>";
			echo "</tr>";
			
			if (count($comenzi) > 0) {
	     		for ($i = 0; $i < count($comenzi); $i++) {
	     			if ($nr_zile_dif[$i] <= $setari_client->zile_alarma_plati && isset($nr_zile_dif[$i])) {
	     				$bg_color = " class=\"redThing\" onmouseout=this.className=\"redThing\" onmouseover=this.className=\"blueThing\"";
	     			}
	     			else $bg_color = " class=\"blueThing\" onmouseout=this.className=\"blueThing\" onmouseover=this.className=\"whiteThing\"";
	     			
	     			echo "<tr $bg_color>";				

     					$firma = Firma::queryLoadById($db, $comenzi[$i]->id_firma_sol, $id_client);
	     				echo "<td align=\"center\"><a href=\"view_firma.php?id=" . $firma->id_firma . "\">" . $firma->nume . "</a></td>";
	     				echo "<td align=\"center\">" . $comenzi[$i]->nr_comanda_sol . "</td>";
	     				echo "<td align=\"center\">" . getDateForUser($comenzi[$i]->data_scadenta_exec) . "</td>";
	     				echo "<td align=\"center\">" . $nr_zile_dif[$i] . "</td>";
	     				echo "<td align=\"center\">";
	     					echo "<input type=\"button\" onclick=\"javascript: fa_plata_incasare(1, " . $comenzi[$i]->id_comanda . ");\" value=\"" . LANG_Do_plata . "\" />";	
	     				echo "</td>";
	     			echo "</tr>";	
	     		}
	     		
	     		$_SESSION['camp_comenzi'] = "data_scadenta_exec"; 
	     		$_SESSION['order_comenzi'] = "DESC";
	     		echo "<tr class=\"capTabel\">";			
	     			echo "<td colspan=\"5\" align=\"right\">";
	     				echo "<input type=\"button\" onclick=\"javascript: multe_comenzi('comenzi_neplatite', 1);\" value=\"" . LANG_More . "\" />";	
	     			echo "</td>";
	     		echo "</tr>";	     		     
			}
			else {
	     		echo "<tr class=\"capTabel\">";			
	     			echo "<td colspan=\"5\" align=\"center\">";
	     				echo LANG_Nu_exista_comenzi_ptr_plata;	
	     			echo "</td>";
	     		echo "</tr>";	     		     		     		     
			}
			
		echo "</table>";
	}
	catch (QueryLoadComandaException $e) {
		redirectOnError(CT_GET_LAST_PLATI);	
	}
	catch (QueryLoadSetariException $e) {
		redirectOnError(CT_LOAD_SETARI);
	}
	catch (QuerySettingsNotExistException $e) {
		redirectOnError(CT_SETTINGS_NOT_EXIST);
	}
    catch (QueryLoadFirmaException $e) {
    	redirectOnError(CT_LOAD_FIRMA_BY_ID);
	}	
}

function stats_hp($db) {
    $id_client = $_SESSION['user_logat']->id_client;
    
    try {
		$values = Comanda::get_nr_comenzi_ultimele_zile($db, $id_client, CT_COMENZI_ULTIMELE_ZILE);
		echo "<table id=\"wrapper\">";		
			echo "<thead>";
				echo "<tr>";
					echo "<th bgcolor=\"#CCCCCC\" colspan=\"2\">" . LANG_Statistici . "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td><b>" . LANG_Comenzi_ultimele . " " . CT_COMENZI_ULTIMELE_ZILE . " " . LANG_ZILE . "</b></td>";
				echo "<td>" . $values[0] . "</td>";
			echo "</tr>";		
			echo "<tr class=\"capTabel\">";
				echo "<td><b>" . LANG_Comenzi_incasate_ultimele . " " . CT_COMENZI_ULTIMELE_ZILE . " " . LANG_ZILE .  "</b></td>";
				echo "<td>" . $values[1] . "</td>";
			echo "</tr>";		
			echo "<tr class=\"capTabel\">";
				echo "<td><b>" . LANG_Comenzi_platite_ultimele . " " . CT_COMENZI_ULTIMELE_ZILE . " " . LANG_ZILE .  "</b></td>";
				echo "<td>" . $values[2] . "</td>";
			echo "</tr>";		
			echo "<tr class=\"capTabel\">";
				echo "<td><b>" . LANG_Comenzi_incasate_partial . " " . CT_COMENZI_ULTIMELE_ZILE . " " . LANG_ZILE .  "</b></td>";
				echo "<td>" . $values[4] . "</td>";
			echo "</tr>";		
			echo "<tr class=\"capTabel\">";
				echo "<td><b>" . LANG_Comenzi_platite_partial . " " . CT_COMENZI_ULTIMELE_ZILE . " " . LANG_ZILE .  "</b></td>";
				echo "<td>" . $values[3] . "</td>";
			echo "</tr>";
		echo "</table>";
    }
    catch (QueryLoadComandaException $e) {
    	redirectOnError(CT_LOAD_COMANDA_FOR_STATS_HP);
    }
}

function check_tooltip() {
	var_dump($_SESSION['user_logat']->tooltip);
	if (isset($_SESSION['user_logat']->tooltip) && !empty($_SESSION['user_logat'])) {
		if ($_SESSION['user_logat']->tooltip == 0) 
			return false;
		else 
			return true;
	}
	
	return true;
}

function output_extra_text($text, $force_draw = false) {
    if ($_SESSION['user_logat']->extra_text == 1 || $force_draw) {
        echo '<div class="extra_text">';
        	echo LANG_GENERIC_TABLE_START . $text . LANG_GENERIC_TABLE_END;
        echo '</div>';
    }
}

function output_extra_text_modal($text, $colSpan) {
    if ($_SESSION['user_logat']->extra_text == 1) {
        return
            '<tr class="capTabel">' . 
                '<td colspan="' . $colSpan . '" align="center">' .
                    '<div class="extra_text_modal">' . LANG_GENERIC_TABLE_MODAL_START . $text . LANG_GENERIC_TABLE_END . '</div>' . 
                '</td>' . 
            '</tr>';
    }
}

function show_tooltip($tooltipHead, $tooltipBody = null, $return = false) {
	if (check_tooltip()) {
		$tooltipHeaderCSS 	= 'cssheader=[dvhdr1]';
		$tooltipBodyCSS 	= 'cssbody=[dvbdy1]';		
		if (!$return) {
			echo 'title="' . $tooltipBodyCSS . " " . $tooltipHeaderCSS . ' header=[' . $tooltipHead . '] body=[' . $tooltipBody . ']"';
			return null;
		}
		else
			return 'title="' . $tooltipBodyCSS . " " . $tooltipHeaderCSS . ' header=[' . $tooltipHead . '] body=[' . $tooltipBody . ']"';
	}
}

function getDateForUser($dateString, $ora = false) {
    // TODO: punere separator in setari client
//	echo $dateString;
    if (!isset($dateString))
        return null;
    
    $separator = CT_DATE_SEPARATOR;//$_SESSION['client_logat']->dateSeparator;
	if ($ora == true) {
        $aux = explode(" ", $dateString);
        $dateString = $aux[0];
        // Impartirea orei
        $aux2 = explode(":", $aux[1]);
        $oraString = $aux2[0]. ":" . $aux2[1];
    }
    $arr = explode("-", $dateString);
    
    if (strlen($dateString) >= 8)
        if ($ora == true)
            return $arr[2].$separator.$arr[1].$separator.$arr[0]." ".$oraString;
        else
            return $arr[2].$separator.$arr[1].$separator.$arr[0];
	else 
		return null;
}

function getDateForServer($dateString, $ora = false) {
	// TODO: punere separator in setari client
    
    if (!isset($dateString) || $dateString == '')
        return null;
    
    $separator = CT_DATE_SEPARATOR;//$_SESSION['client_logat']->dateSeparator;
    if ($ora == true) {
        $aux = explode(" ", $dateString);
        $dateString = $aux[0];
        $oraString = $aux[1];
    }
	$arr = explode(CT_DATE_SEPARATOR, $dateString);
    
	if (strlen($dateString) >= 8)
        if ($ora == true) 
            return $arr[2].$separator.$arr[1].$separator.$arr[0]." ".$oraString;
        else
            return $arr[2].$separator.$arr[1].$separator.$arr[0];
	else 
		return null;
}

function show_status_acte($status_acte) {
	if ($status_acte == 0) return (LANG_Nenecesar);
	if ($status_acte == 1) return (LANG_Necesar_si_neexistent);
    if ($status_acte == 2) return (LANG_Necesar_si_existent);
	if ($status_acte == 3) return (LANG_Nenecesar_si_existent);
}

function render_search_contacts($id_client) {
	$per_pag = $_SESSION['user_logat']->firme_per_pag;
	echo "<div class=\"container\">";
		echo '<table align="left" id="wrapper">';
			echo "<thead>";
				echo "<tr>";
					echo "<th class=\"caption\" colspan=\"4\">" . LANG_Cauta_Contact . "</th>";
				echo "</tr>";
			echo "</thead>";
			echo "<tr class=\"capTabel\">";
				echo "<td align=\"right\">" . LANG_Search_by . "</td>";
				echo "<td>";		
					echo '<input type="text" name="keyword" id="keyword" onkeypress="onEnter(event, \'cauta_contacte\')" /> ';
					echo "<select name=\"camp_search\" id=\"camp_search\">";	
						echo '<option value="-1">' . LANG_All. '</option>';
						echo '<option value="nume">' . LANG_NUME. '</option>';			
						echo '<option value="functie">' . LANG_FUNCTIE_CONTACT. '</option>';								
						echo '<option value="tel_fix">' . LANG_TEL_FIX. '</option>';			
						echo '<option value="tel_fax">' . LANG_TEL_FAX. '</option>';			
						echo '<option value="tel_mobil">' . LANG_TEL_MOBIL. '</option>';			
						echo '<option value="email">' . LANG_EMAIL. '</option>';									
					echo "</select>";
				echo "</td>";
				echo "<td align=\"right\">" . LANG_Per_Page . "</td>";
				echo "<td>";
					echo "<select name=\"per_page\" id=\"per_page\">";
						if (10 == $per_pag) $text = " selected=\"selected\" ";
						else $text = "";
						echo "<option value=\"10\"$text>10</option>";
						if (20 == $per_pag) $text = " selected=\"selected\" ";
						else $text = "";
						echo "<option value=\"20\"$text>20</option>";
						if (30 == $per_pag) $text = " selected=\"selected\" ";
						else $text = "";
						echo "<option value=\"30\"$text>30</option>";
						if (40 == $per_pag) $text = " selected=\"selected\" ";
						else $text = "";
						echo "<option value=\"40\"$text>40</option>";
						if (50 == $per_pag) $text = " selected=\"selected\" ";
						else $text = "";
						echo "<option value=\"50\"$text>50</option>";
					echo "</select>";	
					echo " <input type=\"button\" onclick=\"javascript: cauta_contact(0);\" name=\"search_contacts\" value=\"" . LANG_Cauta . "\" />";
				echo "</td>";
			echo "</tr>";
		echo '</table>';
	echo "</div>";
}

function print_contacts_table($contacts, $total, $per_pag, $value, $camp, $id_client, $pagina) {

?>
<div class="container">
	<table id="wrapper" align="left" width="600">
		<thead>
            <tr>
                <th colspan="6" align="center">Contacte</th>
            </tr>
        </thead>
        <tbody>
            <tr class="paginare">
				<td colspan="6" align="center">
					<?php 
                        if ($total > 0) {                                                
						    echo LANG_Pagina . " "; 
						    
						    $pagini = ceil($total / $per_pag);
                            
                            if ($pagina - CT_PAGINARE_INAINTE_DUPA >= 1) {
                                echo "<a class=\"linkbold\" onclick=\"javascript: cauta_contact(0);\">" . LANG_FIRST . "</a> .. ";                                
                            }
                            
						    for ($i = $pagina - CT_PAGINARE_INAINTE_DUPA ; $i <= $pagina + CT_PAGINARE_INAINTE_DUPA; $i++) {
                                if ($i >= 0 && $i < $pagini) {
                                    if ($i == $pagina) {
							            echo "<a class=\"linkbold\" onclick=\"javascript: cauta_contact($i);\">" . ($i + 1) . "</a> ";
                                    }
                                    else {
                                        echo "<a onclick=\"javascript: cauta_contact($i);\">" . ($i + 1) . "</a> ";                            
                                    }
                                }
						    }
                            if ($pagini - ($pagina + 1) > CT_PAGINARE_INAINTE_DUPA) {
                                echo " .. <a class=\"linkbold\" onclick=\"javascript: cauta_contact($pagini - 1);\">" . LANG_LAST . "</a>";                                
                            }      
                        }
                        else {
                            echo LANG_Nu_sau_gasit_contacte;
                        }
					?>
				</td>
			</tr>
			<tr class="capTabel">
				<td align="center"><b><?php echo LANG_NUME; ?></b></td>
				<td align="center"><b><?php echo LANG_FUNCTIE_CONTACT; ?></b></td>
				<td align="center"><b><?php echo LANG_TEL_FIX; ?></b></td>
				<td align="center"><b><?php echo LANG_TEL_FAX; ?></b></td>
				<td align="center"><b><?php echo LANG_TEL_MOBIL; ?></b></td>
				<td align="center"><b><?php echo LANG_EMAIL; ?></b></td>
			</tr>
		</tbody>
		<?php
			$total = count($contacts);
			for($i = 0; $i < $total; $i++) {
				echo "<tr onmouseout=this.className=\"blueThing\" onmouseover=this.className=\"whiteThing\" class=\"blueThing\">";
					echo "<td align=\"center\">" . $contacts[$i]->nume . "</td>";
					echo "<td align=\"center\">" . $contacts[$i]->functie . "</td>";
					echo "<td align=\"center\">" . $contacts[$i]->tel_fix . "</td>";
					echo "<td align=\"center\">" . $contacts[$i]->tel_fax . "</td>";
					echo "<td align=\"center\">" . $contacts[$i]->tel_mobil . "</td>";
					echo "<td align=\"center\">" . $contacts[$i]->email . "</td>";
				echo "</tr>";
			}
		?>
	</table>
</div>    
<?php
}

function titlu_pagina($arrLinks, $help_page = null) {
     $total = count($arrLinks); 
     $poz = 0;	     
	 echo '<div class="sectionTitle" id="sectionTitle">';
	 	echo '<table class="textInSectionTtitle" width="100%">';
	 		echo "<tr>";
	 			echo '<td width="75%" align="left">';
				     foreach ($arrLinks as $titlu => $link) {
				          if ($poz == $total - 1) $tx = "";
				          else $tx = " : ";
				          if (!empty($link)) echo "<a class=\"textInSectionTtitle\" href=\"{$link}\">$titlu</a>$tx";
				          else echo $titlu . $tx;
				          $poz++;		
				     }
				echo "</td>";
				if (!empty($help_page)) {
	 				echo '<td width="25%" align="right">';
						echo '<a href="help.php?page=' . $help_page . '"><img border="0" src="images/help_me.png" /></a>';
					echo "</td>";
				}
			echo "</tr>";
		echo "</table>";
     echo "</div>";
}

function buton_final_modal_ok($valoare_buton, $name, $function) {
	$a = '<button type="submit" class="button_final" name="' . $name . '" onclick="javascript: ' . $function. ';">';
		$a .= '<span class="pngfix"><img align="left" src="' . IMG_PATH . 'ok.png" border="0" />&nbsp; ' . $valoare_buton . '</span>';
	$a .= '</button>';
	return $a;
}

function buton_final_ok($valoare_buton, $name) {
    ?>
	<button type="submit" class="button_final" name="<?php echo $name; ?>">
		<span class="pngfix">
            <div class="imagine_button_final">
                <img align="center" src="<?php echo IMG_PATH . "ok.png"; ?>" border="0" />&nbsp; <?php echo $valoare_buton; ?>
            </div>
        </span>
	</button>
    <?php
}

function buton_final_cancel($valoare_buton, $pagina) {
    ?>
	<button class="button_final" type="button" onclick="javascript: cancel('<?php echo $pagina; ?>');">
		<span class="pngfix">
            <div class="imagine_button_final">
                <img align="center" src="<?php echo IMG_PATH . "cancel.png"; ?>" border="0" />&nbsp; <?php echo $valoare_buton; ?>
            </div>
        </span>
	</button>
    <?php
}

function buton_final_modal_cancel($valoare_buton, $functieJS) {
	$a = '<button class="button_final" type="button" onclick="javascript: ' . $functieJS . '; return; ">';
		$a .= '<span class="pngfix"><a href="./show_comenzi.php"><img align="left" src="' . IMG_PATH . 'cancel.png" border="0" />&nbsp; ' . $valoare_buton . '</a></span>';
	$a .= '</button>';
	return $a;
}

function view_firma($firma, $currencies) {
    
	?>
	<div class="container">		
		<?php if (isset($forprint)) echo '<div class="sectionTitle">' . $firma->nume . "</div><br />"; ?>
		<table border="0" align="left" cellpadding="0" cellspacing="0">
			<tr>
		   		<td valign="top">   
			 		<table border="0" id="wrapper">
			 			<thead>
			 				<tr>
			 					<th colspan="2" align="center"><?php echo LANG_Detalii_firma; ?></th>
			 				</tr>
			 			</thead>
				 		<tr>
					 		<td align="right"><b><?php echo LANG_NUME_FIRMA; ?></b></td>
					 		<td>
								<?php echo $firma->nume; ?>					
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_CF; ?></b></td>
					 		<td>
    							<?php echo $firma->cf; ?>					
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_RC; ?></b></td>
					 		<td>
    							<?php echo $firma->rc; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_TEL_FIX; ?></b></td>
					 		<td>
								<?php echo $firma->tel_fix; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_TEL_FAX; ?></b></td>
					 		<td>
								<?php echo $firma->tel_fax; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_TEL_MOBIL; ?></b></td>
					 		<td>
								<?php echo $firma->tel_mobil; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_EMAIL; ?></b></td>
					 		<td>
								<?php echo $firma->email; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_WEB; ?></b></td>
					 		<td>
								<?php echo $firma->web; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_TIP_FIRMA; ?><b/></td>
					 		<td>
								<?php 
                                    if ($firma->tip == CT_TIP_FIRMA_ALL) echo LANG_FIRMA_TRANSPORTATOR . ", " . LANG_FIRMA_SPEDITII . ", " . LANG_FIRMA_FABRICA; 
									if ($firma->tip == CT_TIP_FIRMA_TRANSPORTATOR) echo LANG_FIRMA_TRANSPORTATOR; 
									if ($firma->tip == CT_TIP_FIRMA_SPEDITII) echo LANG_FIRMA_SPEDITII; 
									if ($firma->tip == CT_TIP_FIRMA_FABRICA) echo LANG_FIRMA_FABRICA; 
								?>
					 		</td>
				 		</tr>
				 		<tr class="capTabel">
				 			<td align="right"><b><?php echo LANG_Comentariu; ?><b/></td>
				 			<td><?php echo $firma->comentariu; ?></td>
				 		</tr>
				 		<tr class="capTabel">
				 			<td align="right"><b><?php echo LANG_Calitate_firma; ?><b/></td>
				 			<td>
				 				<?php 
				 					switch ($firma->calitate_firma) {
				 						case CT_FIRMA_SERIOASA:
				 							echo LANG_Firma_serioasa;
				 							break;
				 						case CT_FIRMA_NESERIOASA:
				 							echo LANG_Firma_neserioasa;
				 							break;
				 					} 
				 				?>
				 			</td>
				 		</tr>				 		
			 		</table>
		   		</td>
		   		<td width="40"></td>
		   		<td valign="top">
		      		<table border="0" id="wrapper">
		      			<thead>
		      				<tr>
		      					<th colspan="2" align="center"><b><?php echo LANG_Adresa_firma; ?></b></th>
		      				</tr>
		      			</thead>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_ADRESA; ?></b></td>
					 		<td>
								<?php echo $firma->adresa->adresa; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_ORAS; ?></b></td>
					 		<td>
								<?php echo $firma->adresa->oras; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_JUDET; ?></b></td>
					 		<td>
								<?php echo $firma->adresa->judet; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_COD_POSTAL; ?></b></td>
					 		<td>
								<?php echo $firma->adresa->cod_postal; ?>
							</td>
				 		</tr>
				 		<tr class="capTabel">
					 		<td align="right"><b><?php echo LANG_TARA; ?></b></td>
					 		<td>
								<?php echo $firma->adresa->tara; ?>
							</td>
				 		</tr>					 		
			 		</table>
		   		</td>
		  	</tr>
	  	</table>
	  	</div>
	  	<div class="container">
		  	<table border="0" align="left" cellpadding="0" cellspacing="0" width="700">
			  	<tr>		 	
			 	 	<td id="td_conturi" valign="top" colspan="3">	
			 	 			
	 					<?php render_cont_table($firma, "view", $currencies, CT_CONT_FIRMA); ?>				 	 	
			 	 	</td>
			  	</tr>			 
		  	</table>
	  	</div>
	  	<div class="container">
		  	<table border="0" align="left" cellpadding="0" cellspacing="0" width="700">
			  	<tr>	 	
			 	 	<td id="td_contacte" valign="top" colspan="3">				 	 			 		
		 				<?php render_contact_table($firma, "view", $currencies, CT_CONT_FIRMA); ?>
			 	 	</td>
			  	</tr>			 
	 		</table>
 		</div>
	  	<div class="container">
		  	<table border="0" align="left" cellpadding="0" cellspacing="0" width="700">
			  	<tr>	 	
			 	 	<td id="td_contacte" valign="top" colspan="3">				 	 			 		
		 				<?php render_rute_table($firma, "view"); ?>
			 	 	</td>
			  	</tr>			 
	 		</table>
 		</div> 		
	<?php
}

function print_firmaWithOO($firma, $currencies) {
	require_once(INCLUDE_PATH . 'constants.inc');
		
	session_start();
	
	/*
	 * populat content.xml cu datele din comanda
	 */
	
	$styles_xml = file_get_contents('printTemplates/styles_firma.xml');
	

	$content_xml = $styles_xml;

	require_once('printTemplates/body_firma.php');

	
	/*
	 * salvez acest content.xml in structura de odt
	 */
	
	$user_folder = USERS_PATH . $_SESSION['user_logat']->id_user . '/firma_dez';
	
	file_put_contents($user_folder . "/content.xml", $content_xml);
	
	/*
	 * creat arhiva zip cu structura, inclusiv poza logo-ului firmei
	 * 
	 */
	
	$output_odt = USERS_PATH . $_SESSION['user_logat']->id_user;
	$current_dir = system("pwd > /dev/null", $retval);

	chdir($user_folder);	
	$last_line = system("zip -r $output_odt/firma_" . $firma->id_firma . ".odt Configurations2 META-INF Pictures Thumbnails content.xml layout-cache meta.xml mimetype settings.xml styles.xml > /dev/null", $retval);
	chdir($current_dir . "/");
	
	$cale_fisier_odt = "$output_odt/firma_" . $firma->id_firma . ".odt";
	$cale_fisier_pdf = "file://$output_odt/firma_" . $firma->id_firma . ".pdf";
	
	/*
	 * rulat un proces linux de transformare in PDF
	 * 
	 */

	$last_line = exec("/bin/to_pdf.sh $cale_fisier_odt $cale_fisier_pdf > /dev/null", $ret_val);

	/*
	 * voi sterge fisierul odt care l-am generat
	 */
	
	unlink($cale_fisier_odt);
}

function getCurrentUrlDirectory() {
    $path = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
    for ($i = strlen($path)-1; $i--; $i > 0)
        if ($path[$i] == '/')
            break;                          
    $path = substr($path, 0, $i+1);
    return $path;
}

function printAddressRow($adresa) {
    $text_adresa = '';
    if ($adresa->tara != '')
        $text_adresa .= $adresa->tara . ", ";
    if ($adresa->oras != '')
        $text_adresa .= $adresa->oras . ", ";
    if ($adresa->judet != '')
        $text_adresa .= $adresa->judet . ", ";
    if ($adresa->cod_postal != '')
        $text_adresa .= $adresa->cod_postal . ", ";
    if ($adresa->adresa != '')
        $text_adresa .= $adresa->adresa . ", ";
    if ($adresa->nume_firma != '')
        $text_adresa .= $adresa->nume_firma . ", ";
    if ($adresa->impexp != '')
        $text_adresa .= $adresa->impexp . ", ";
    if ($text_adresa[strlen($text_adresa) - 1] == ",")
        $text_adresa[strlen($text_adresa) - 1] = "";
    return $text_adresa;    
}

function print_contractWithOO($client, $user_admin) {
	
	/*
	 * populat content.xml cu datele din contract
	 */
	
	$styles_xml = file_get_contents('printTemplates/styles_contract.xml');
	

	$content_xml = $styles_xml;
	require_once('printTemplates/body_contract.php');
	
	/*
	 * salvez acest content.xml in structura de odt
	 */
	
	$user_folder = USERS_PATH . $_SESSION['user_logat']->id_user . '/contract_dez';
	
	file_put_contents($user_folder . "/content.xml", $content_xml);
	
	/*
	 * creat arhiva zip cu structura, inclusiv poza logo-ului firmei
	 */		

	$output_odt = USERS_PATH . $_SESSION['user_logat']->id_user;
	$current_dir = system("pwd > /dev/null", $retval);

	chdir($user_folder);	
	$last_line = system("zip -r $output_odt/contract_" . $client->id_client . ".odt Configurations2 META-INF Pictures Thumbnails content.xml layout-cache meta.xml mimetype settings.xml styles.xml > /dev/null", $retval);
	chdir($current_dir . "/");
	
	$cale_fisier_odt = "$output_odt/contract_" . $client->id_client . ".odt";
	$cale_fisier_pdf = "file://$output_odt/contract_" . $client->id_client . ".pdf";
	
	/*
	 * rulat un proces linux de transformare in PDF
	 */

	$last_line = exec("/bin/to_pdf.sh $cale_fisier_odt $cale_fisier_pdf > /dev/null", $ret_val);

	/*
	 * mai bine sterg fisierul odt care l-am generat sa nu ramana acolo
	 */
	
	unlink($cale_fisier_odt);
}

function print_comandaWithOO($comanda, $db, $client, $firma_exec, $contact_nume, $setari_client) {
	
    global $currencies;
	/*
	 * populat content.xml cu datele din comanda
	 */
	
	$styles_xml = file_get_contents('printTemplates/styles_comanda.xml');
	

	$content_xml = $styles_xml;
	require_once('printTemplates/header_comanda.php');
	require_once('printTemplates/body_comanda.php');
	require_once('printTemplates/end_comanda.php');
	
	/*
	 * salvez acest content.xml in structura de odt
	 */
	
	$user_folder = USERS_PATH . $_SESSION['user_logat']->id_user . '/comanda_dez';
	
	file_put_contents($user_folder . "/content.xml", $content_xml);
	
	/*
	 * acuma ma voi ocupa de fisierul styles xml unde este footerul
	 */
	
	$styles_xml = "";
	require_once('printTemplates/styles_comanda.php');
	file_put_contents($user_folder . "/styles.xml", $styles_xml);
	
	/*
	 * creat arhiva zip cu structura, inclusiv poza logo-ului firmei
	 * 
	 */
	
	$output_odt = USERS_PATH . $_SESSION['user_logat']->id_user;
	$current_dir = system("pwd > /dev/null", $retval);

	chdir($user_folder);	
	$last_line = system("zip -r $output_odt/comanda_" . $comanda->id_comanda . ".odt Configurations2 META-INF Pictures Thumbnails content.xml layout-cache meta.xml mimetype settings.xml styles.xml > /dev/null", $retval);
	chdir($current_dir . "/");
	
	$cale_fisier_odt = "$output_odt/comanda_" . $comanda->id_comanda . ".odt";
	$cale_fisier_pdf = "file://$output_odt/comanda_" . $comanda->id_comanda . ".pdf";
	$cale_fisier_termeni = "file://$output_odt/termeni.html";
	
	/*
	 * rulat un proces linux de transformare in PDF
	 */

	$last_line = exec("/bin/to_pdf.sh $cale_fisier_odt $cale_fisier_pdf $cale_fisier_termeni > /dev/null", $ret_val);

	/*
	 * voi sterge fisierul odt care l-am generat
	 */
	
	unlink($cale_fisier_odt);
}

function print_facturaWithOO($db, $comanda, $firma, $moneda, $curs, $curs_invers, $text_factura, $serie_factura, $tva_inclus, $tva, $nume_delegat
                    , $mijloc_transport, $cnp, $serie_ci, $data) {
    
    global $currencies;
    
    $cu_tva = true;
    if (!isset($tva) || $tva == '' || $tva == '0')
		$cu_tva = false;
		
	$suma = $comanda->suma_totala_sol;
	if ($comanda->moneda_sol != $moneda) {
		if ($curs != '')
			$suma_finala = $suma * $curs;
		else
			$suma_finala = round($suma / $curs_invers, 2);
	}
	else
		$suma_finala = $suma;
	
	if ($tva_inclus == "1") {
		$suma_fara_tva = round(($suma_finala * 100) / (100 + $tva), 2);
		$suma_cu_tva = $suma_finala;
	}
	else {
		$suma_fara_tva = $suma_finala;
		$suma_cu_tva = round(($suma_finala * (100 + $tva)) / 100, 2);
		$suma_finala = $suma_cu_tva;
	}
	
    $client = $_SESSION['client_logat'];
    $contClient = '';
    $bancaClient = '';
    $monedaClient = '';
    foreach($client->conturi as $cont)
        if ($cont->moneda == $moneda) {
            $contClient = $cont->cont;
            $bancaClient = $cont->banca;
            $monedaClient = $cont->moneda;
        }
        
    $contFirma = '';
    $bancaFirma = '';
    $monedaFirma = '';
    foreach($firma->conturi as $cont)
        if ($cont->moneda == $moneda) {
            $contFirma = $cont->cont;
            $bancaFirma = $cont->banca;
            $monedaFirma = $cont->moneda;
        }
	/*
	 * populat content.xml cu datele din factura
	 */
	
	$styles_xml = file_get_contents('printTemplates/styles_factura.xml');
	

	$content_xml = $styles_xml;
	require_once('printTemplates/body_factura.php');
	
	/*
	 * salvez acest content.xml in structura de odt
	 */
	
	$user_folder = USERS_PATH . $_SESSION['user_logat']->id_user . '/factura_dez';
	
	file_put_contents($user_folder . "/content.xml", $content_xml);
	
	/*
	 * acuma ma voi ocupa de fisierul styles xml unde este footerul
	 */
	
	$styles_xml = "";
	require_once('printTemplates/styles_factura.php');
	file_put_contents($user_folder . "/styles.xml", $styles_xml);
	
	/*
	 * creat arhiva zip cu structura, inclusiv poza logo-ului firmei
	 * 
	 */
	
	$output_odt = USERS_PATH . $_SESSION['user_logat']->id_user;
	$current_dir = system("pwd > /dev/null", $retval);

	chdir($user_folder);	
	$last_line = system("zip -r $output_odt/factura_" . $comanda->id_comanda . ".odt Configurations2 META-INF Pictures Thumbnails content.xml layout-cache meta.xml mimetype settings.xml styles.xml > /dev/null", $retval);
	chdir($current_dir . "/");
	
	$cale_fisier_odt = "$output_odt/factura_" . $comanda->id_comanda . ".odt";
	$cale_fisier_pdf = "file://$output_odt/factura_" . $comanda->id_comanda . ".pdf";
	
	/*
	 * rulat un proces linux de transformare in PDF
	 * 
	 */

	$last_line = exec("/bin/to_pdf.sh $cale_fisier_odt $cale_fisier_pdf > /dev/null", $ret_val);

	/*
	 * voi sterge fisierul odt care l-am generat
	 */
	
	unlink($cale_fisier_odt);
	
}

function print_factura_clientWithOO($db, $client, $factura, $nume_user) {                 
    global $currencies;
    $curs = CT_CURS_EURO;
    
    $suma_finala = round($factura->suma * $curs, 2);
    $text_factura = LANG_Abonament_cont_onlinelogistics . " " . getDateForUser($factura->data_inceput) . " - " . getDateForUser($factura->data_sfarsit) . LANG_conform_contract_nr . CT_PREFIX_CONTRACT . $client->id_client . " / " . getDateForUser($client->data_inreg);

    $contClient = '';
    $bancaClient = '';
    $monedaClient = '';
    
    foreach ($client->conturi as $cont)
        if ($cont->moneda == $moneda) {
            $contClient = $cont->cont;
            $bancaClient = $cont->banca;
            $monedaClient = $cont->moneda;
        }
        
	/*
	 * populat content.xml cu datele din factura
	 */
	
	$styles_xml = file_get_contents('printTemplates/styles_factura_client.xml');
	
	$content_xml = $styles_xml;
	require_once('printTemplates/body_factura_client.php');
	
	/*
	 * salvez acest content.xml in structura de odt
	 */
	
	$user_folder = USERS_PATH . $_SESSION['user_logat']->id_user . '/factura_client_dez';
	
	file_put_contents($user_folder . "/content.xml", $content_xml);
	
	/*
	 * acuma ma voi ocupa de fisierul styles xml unde este footerul
	 */
	
	$styles_xml = "";
	require_once('printTemplates/styles_factura_client.php');
	file_put_contents($user_folder . "/styles.xml", $styles_xml);
	
	/*
	 * creat arhiva zip cu structura, inclusiv poza logo-ului firmei
	 * 
	 */
	
	$output_odt = USERS_PATH . $_SESSION['user_logat']->id_user;
	$current_dir = system("pwd > /dev/null", $retval);

	chdir($user_folder);	
	$last_line = system("zip -r $output_odt/factura_client_" . $factura->id_factura . ".odt Configurations2 META-INF Thumbnails Pictures content.xml layout-cache meta.xml mimetype settings.xml styles.xml > /dev/null", $retval);
	chdir($current_dir . "/");
	
	$cale_fisier_odt = "$output_odt/factura_client_" . $factura->id_factura . ".odt";
	$cale_fisier_pdf = "file://$output_odt/factura_client_" . $factura->id_factura . ".pdf";
	
	/*
	 * rulat un proces linux de transformare in PDF
	 * 
	 */

	$last_line = exec("/bin/to_pdf.sh $cale_fisier_odt $cale_fisier_pdf > /dev/null", $ret_val);

	/*
	 * voi sterge fisierul odt care l-am generat
	 */
	
	//unlink($cale_fisier_odt);
}

function view_comanda($comanda, $currencies = null) {
	// TODO: Afisarea starii platii comenzii... - ultima data in care s-a facut plata...
?>
	<div class="containter">
		<table align="left">
			<tr class="capTabel">
				<td valign="top">
					<table id="wrapper">
						<thead>
							<tr>
								<th colspan="4" align="center"><?php echo LANG_DATE_SOLICITANT; ?></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan="2"><?php echo LANG_Firma_solicitant; ?></td>
								<td colspan="2"><strong><?php echo $comanda->_external_firma_sol; ?></strong></td>
							</tr>							
							<tr>
								<td colspan="2"><?php echo LANG_Contact_sol; ?></td>
								<td colspan="2"><?php echo $comanda->_external_contact_sol; ?></td>
							</tr>							
							<tr>
								<td><?php echo LANG_Numar_factura_sol; ?></td>
								<td><?php echo $comanda->nr_factura_sol; ?></td>
								<td><?php echo LANG_Din; ?></td>
								<td><?php echo getDateForUser($comanda->data_factura_sol); ?></td>
							</tr>							
							<tr>
								<td><?php echo LANG_Numar_comanda_sol; ?></td>
								<td><?php echo $comanda->nr_comanda_sol; ?></td>
								<td><?php echo LANG_Din; ?></td>
								<td><?php echo getDateForUser($comanda->data_comanda_sol); ?></td>
							</tr>						
							<tr>
								<td><?php echo LANG_Suma_sol; ?></td>
								<td><?php echo prepareFloatForUser($comanda->suma_sol) . " ". $currencies[$comanda->moneda_sol]; ?></td>
								<td><?php echo LANG_taxe_supl_to_sol; ?></td>
								<td><?php echo prepareFloatForUser($comanda->taxe_supl_to_sol) . " ". $currencies[$comanda->moneda_sol]; ?></td>
							</tr>						
							<tr>
								<td><?php echo LANG_Penalizare_from_sol; ?></td>
								<td><?php echo prepareFloatForUser($comanda->penaliz_from_sol) . " ". $currencies[$comanda->moneda_sol]; ?></td>
								<td><strong><?php echo LANG_suma_totala_sol; ?></strong></td>
								<td><strong><?php echo prepareFloatForUser($comanda->suma_totala_sol) . " ". $currencies[$comanda->moneda_sol]; ?></strong></td>
							</tr>					
							<tr>
								<td><?php echo LANG_Data_tr_acte_sol; ?></td>
								<td><?php echo getDateForUser($comanda->data_tr_acte_sol); ?></td>
								<td><?php echo LANG_Data_scadenta_sol; ?></td>
								<td><?php echo getDateForUser($comanda->data_scadenta_sol); ?></td>
							</tr>					
							<tr>
								<td><?php echo LANG_Coment_sol; ?></td>
								<td colspan="3"><?php echo $comanda->coment_sol; ?></td>
							</tr>
							<tr>
								<td>
									<?php echo LANG_ACTE_NECESARE; ?>: 
								</td>
								<td colspan="3">
									
									<input disabled type="checkbox" <?php if ($comanda->_cmr_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_cmr_sol == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_CMR_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_factura_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_factura_sol == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Factura_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_carnet_tir_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_carnet_tir_sol == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Carnet_tir_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_decl_vamala_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_decl_vamala_sol == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Declaratie_vamala_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_alte_acte_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_alte_acte_sol == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Alte_acte_sol; ?>
									
								</td>
							</tr>
							<tr>
								<td>
									<?php echo LANG_ACTE_TRIMISE; ?>: 
								</td>
								<td colspan="3">
									
									<input disabled type="checkbox" <?php if ($comanda->_cmr_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_cmr_sol == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_CMR_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_factura_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_factura_sol == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Factura_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_carnet_tir_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_carnet_tir_sol == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Carnet_tir_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_decl_vamala_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_decl_vamala_sol == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Declaratie_vamala_sol; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_alte_acte_sol == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_alte_acte_sol == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Alte_acte_sol; ?>
																	
								</td>							
							</tr>
						</tbody>
					</table>
				</td>
				<td valign="top">
					<table id="wrapper">
						<thead>
							<tr>
								<th colspan="4" align="center"><?php echo LANG_DATE_EXECUTANT; ?></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan="2"><?php echo LANG_Firma_exec; ?></td>
								<td colspan="2"><strong><?php echo $comanda->_external_firma_exec; ?></strong></td>
							</tr>
							<tr>
								<td colspan="2"><?php echo LANG_Contact_exec; ?></td>
								<td colspan="2"><?php echo $comanda->_external_contact_exec; ?></td>
							</tr>
							<tr>
								<td><?php echo LANG_Numar_factura_exec; ?></td>
								<td><?php echo $comanda->nr_factura_exec; ?></td>
								<td><?php echo LANG_Din; ?></td>
								<td><?php echo getDateForUser($comanda->data_factura_exec); ?></td>
							</tr>
							<tr>
								<td><?php echo LANG_Numar_comanda; ?></td>
								<td><?php echo $comanda->nr_comanda_exec; ?></td>
								<td><?php echo LANG_Din; ?></td>
								<td><?php echo getDateForUser($comanda->data_comenzii); ?></td>
							</tr>
							<tr>
								<td><?php echo LANG_Suma_exec; ?></td>
								<td><?php echo prepareFloatForUser($comanda->suma_exec) . " ". $currencies[$comanda->moneda_exec]; ?></td>
								<td><?php echo LANG_Taxa_suplimentara_from_exec; ?></td>
								<td><?php echo prepareFloatForUser($comanda->taxe_supl_from_exec) . " ". $currencies[$comanda->moneda_exec]; ?></td>
							</tr>
							<tr>
								<td><?php echo LANG_Penalizare_to_exec; ?></td>
								<td><?php echo prepareFloatForUser($comanda->penaliz_to_exec) . " ". $currencies[$comanda->moneda_exec]; ?></td>
								<td><strong><?php echo LANG_Suma_totala_exec; ?></strong></td>
								<td><strong><?php echo prepareFloatForUser($comanda->suma_totala_exec) . " ". $currencies[$comanda->moneda_exec]; ?></strong></td>
							</tr>
							<tr>
								<td><?php echo LANG_data_primirii_acte_exec; ?></td>
								<td><?php echo getDateForUser($comanda->data_primirii_acte_exec); ?></td>
								<td><?php echo LANG_Data_scadenta_exec; ?></td>
								<td><?php echo getDateForUser($comanda->data_scadenta_exec); ?></td>
							</tr>
							<tr>
								<td><?php echo LANG_Coment_exec; ?></td>
								<td colspan="3"><?php echo $comanda->coment_exec; ?></td>
							</tr>	
							<tr>
								<td>
									<?php echo LANG_ACTE_NECESARE; ?>: 
								</td>
								<td colspan="3">
																	
									<input disabled type="checkbox" <?php if ($comanda->_cmr_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_cmr_exec == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_CMR_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_factura_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_factura_exec == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Factura_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_carnet_tir_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_carnet_tir_exec == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Carnet_tir_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_decl_vamala_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_decl_vamala_exec == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Declaratie_vamala_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_alte_acte_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_alte_acte_exec == CT_ACT_NECESAR_SI_NEEXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Alte_acte_exec; ?>
																		
								</td>
							</tr>
							<tr>
								<td>
									<?php echo LANG_ACTE_TRIMISE; ?>: 
								</td>
								<td colspan="3">
									
									<input disabled type="checkbox" <?php if ($comanda->_cmr_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_cmr_exec == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_CMR_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_factura_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_factura_exec == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Factura_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_carnet_tir_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_carnet_tir_exec == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Carnet_tir_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_decl_vamala_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_decl_vamala_exec == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Declaratie_vamala_exec; ?>
									
									<input disabled type="checkbox" <?php if ($comanda->_alte_acte_exec == CT_ACT_NECESAR_SI_EXISTENT || $comanda->_alte_acte_exec == CT_ACT_NENECESAR_SI_EXISTENT) echo 'checked="checked"'; ?>/>
									<?php echo LANG_Alte_acte_exec; ?>
								</td>							
							</tr>													
						</tbody>
					</table>
				</td>
			</tr>
			<tr>
				<td align="left">
					<?php 
						// Calculare ultima plata / incasare
						$suma_plata = 0;
						$suma_incasare = 0;
						$ult_plata = null;
						$ult_incasare = null;
						
						foreach($comanda->plati as $plata) {
							if ($plata->tip == CT_PLATA_INCASARE) {
								if ($ult_incasare == null)
									$ult_incasare = $plata;
								$suma_incasare += $plata->suma;
							}
							else {
								if ($ult_plata == null)
									$ult_plata = $plata;
								$suma_plata += $plata->suma;
							}							
						}
					?>
					<table>
						<tr>
							<td>
								<?php 
									echo LANG_Stare_incasare_comanda.": <strong>";
										if ($comanda->stare_incasare_sol == CT_COMANDA_NEINCASATA)
											echo LANG_Neincasata;
										if ($comanda->stare_incasare_sol == CT_COMANDA_INCASATA_PARTIAL)
											echo LANG_Incasata_partial;
										if ($comanda->stare_incasare_sol == CT_COMANDA_INCASATA)
											echo LANG_Incasata;
									echo "</strong> (".prepareFloatForUser($suma_incasare)." ". $currencies[$comanda->moneda_sol] . ")";
									echo "<br />";
									echo LANG_Data_ultimei_incasari.": <strong>". getDateForUser($ult_incasare->data);
									echo "<br />";
								?>
							</td>
							<td>
								<button onclick="javascript: document.location='view_incasare.php?numar_comanda=<?php echo $comanda->nr_comanda_exec; ?>';" class="buton"><?php echo LANG_Arata_incasarile; ?></button>
							</td>
						</tr>
					</table>
				</td>
				<td align="left">
					<table>
						<tr>
							<td>
								<?php
									echo LANG_Stare_plata_comanda.": <strong>";
										if ($comanda->stare_plata_exec == CT_COMANDA_NEPLATITA)
											echo LANG_Neplatita;
										if ($comanda->stare_plata_exec == CT_COMANDA_PLATITA_PARTIAL)
											echo LANG_Platita_partial;
										if ($comanda->stare_plata_exec == CT_COMANDA_PLATITA)
											echo LANG_Platita;
									echo "</strong> (".prepareFloatForUser($suma_plata)." ". $currencies[$comanda->moneda_exec] . ")";
									echo "<br />";
									echo LANG_Data_ultimei_plati.": <strong>". getDateForUser($ult_plata->data);
									echo "<br />";
								?>
							</td>
							<td>
								<button onclick="javascript: document.location='view_plata.php?numar_comanda=<?php echo $comanda->nr_comanda_exec; ?>';" class="buton"><?php echo LANG_Arata_platile; ?></button>
							</td>
						</tr>
					</table>					
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<table id="wrapper" width="100%">
						<thead>
							<tr>
								<th align="center" colspan="5"><?php echo LANG_DATE_COMANDA; ?></th>
							</tr>
						</thead>
						<tbody class="capTabel">								
							<tr>
								<td><?php echo LANG_Telefon_sofer . ": " . $comanda->tel_sofer; ?></td>
								<td><?php echo LANG_Nume_sofer . ": " . $comanda->nume_sofer; ?></td>
								<td><?php echo LANG_Numar_inmatriculare . ": " . $comanda->nr_inmatriculare; ?></td>									
								<td><?php echo LANG_Fel_camion . ": " . $comanda->fel_camion; ?></td>
							</tr>
						</tbody>
					</table>
				</td>
			</tr>
			<tr>
				<td colspan="2">					
					<?php render_adresa($comanda, CT_ADRESA_COMANDA_INCARCARE, CT_ADRESA_COMANDA, 'adrese_incarcare', 1); ?>
				</td>
			</tr>
			<tr>
				<td colspan="2">					
					<?php render_adresa($comanda, CT_ADRESA_COMANDA_DESCARCARE, CT_ADRESA_COMANDA, 'adrese_descarcare', 1); ?>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<?php render_adresa($comanda, CT_ADRESA_COMANDA_VAMA_IMPORT, CT_ADRESA_COMANDA, 'vama_import', 1); ?>
				</td>
			</tr>
			<tr>
				<td colspan="2">
				    <?php render_adresa($comanda, CT_ADRESA_COMANDA_VAMA_EXPORT, CT_ADRESA_COMANDA, 'vama_export', 1); ?>
				</td>
			</tr>			
		</table>
   	</div> 
   	
<?php
}

function prepareFloatForUser($number) { 
    if ($number == '')
        $number = '0';    
    $number = str_replace(".", ",", $number);
    $returnNumber = null;
    if (($aux = strpos($number, ",")) === false)
        $pos = strlen($number);
    else
        $pos = $aux;            

    $returnNumber = substr($number, $pos, strlen($number) - $pos);
    if ($returnNumber == "")
        $returnNumber = ",00";
    $j = 0;
    for ($i = $pos - 1; $i >= 0; $i--) {
        $aux = (string)$number[$i];          
        $returnNumber = $aux . $returnNumber;
        $j++;
        if ($j % 3 == 0 && $i > 0)
            $returnNumber = "." . $returnNumber;
    }
    return $returnNumber;
}            

function prepareIntForUser($number) {    
    if ($number == '')
        $number = '0';
    $number = (string)$number;
    $returnNumber = null;
    $j = 0;
    for ($i = strlen($number) - 1; $i >= 0; $i--) {
        $aux = (string)$number[$i];          
        $returnNumber = $aux . $returnNumber;
        $j++;
        if ($j % 3 == 0 && $i > 0)
            $returnNumber = "." . $returnNumber;
    }
    return $returnNumber;
}                                                  

function prepareNumberForServer($number) {
    $number = str_replace(".", "", $number);        
    $number = str_replace(",", ".", $number);       
    return $number;
}

function render_plati_client($db, $pagina, $per_pag, $id_client, $ciclu, $tip_abon) {
    global $currencies;
    try {
        $plati = Client::getPlatiById($db, $id_client, $pagina, $per_pag);
    }
    catch (QueryGetPlatiByClientException $e) {
        redirectOnError(CT_RENDER_PLATI_CLIENT);
    }    

    echo "<div id=\"plati\">";
        echo "<table id=\"wrapper\" width=\"700\">";
            echo "<thead>";
                echo "<tr>";
                    echo "<th align=\"center\" colspan=\"7\">" . LANG_Stare_Facturi . "</th>";
                echo "</tr>";                        
            echo "</thead>";
            echo "<tbody>";           
                    echo "<tr class=\"paginare\">"; 
                        if ($plati[0]['total'] == 0) {
                            echo "<td colspan=\"2\" width=\"500\" align=\"center\">" . LANG_Nu_Exista_Plati . "</td>";
                        }
                        else { 
                                echo "<td align=\"center\" colspan=\"6\">" . LANG_Pagina;
                                    $nr_pagini = ceil($plati[0]['total'] / $per_pag);
                                    for ($j = 0; $j < $nr_pagini; $j++) {
                                        if ($pagina == $j) echo " <a class=\"linkbold\" onclick=\"javascript: arata_plati_client($id_client, " . $j . ", $per_pag, 'plati');\">" . ($j + 1) . "</a>";
                                        else echo " <a onclick=\"javascript: arata_plati_client($id_client, " . $j . ", $per_pag, 'plati');\">" . ($j + 1) . "</a>";
                                    }
                                echo "</td>";
                            echo "</tr>";
                            echo "<tr class=\"capTabel\">";
                                echo "<td><b>" . LANG_Nr_Factura . "</b></td>";
                                echo "<td><b>" . LANG_Data . "</b></td>";
                                echo "<td><b>" . LANG_Suma . "</b></td>";
                                echo "<td><b>" . LANG_Perioada . "</b></td>";
                                echo "<td><b>" . LANG_Status . "</b></td>";
                                echo "<td><b>" . LANG_Optiuni . "</b></td>";
                            echo "</tr>";
                        echo "</tbody>";
                        $reducere = 0;
                        if ($ciclu == CT_CICLU_PLATA_2) $reducere = CT_ABONAMENT_TIP_2 / 2; 
                        if ($ciclu == CT_CICLU_PLATA_3) $reducere = CT_ABONAMENT_TIP_3 * 2;
                        
                        for ($i = 1; $i < count($plati); $i++) {
                            echo "<tr class=\"randTabel\">";
                                echo "<td>" . $plati[$i]['nr_factura'] . "</td>";                            
                                echo "<td>" . getDateForUser($plati[$i]['data']) . "</td>"; 
                                if ($reducere > 0)                           
                               		echo "<td>"  . $plati[$i]['suma'] . " - " . $reducere . " = " . ($plati[$i]['suma'] - $reducere) . "</td>";
                               	else echo "<td>"  . $plati[$i]['suma'] . " " . $currencies[$plati[$i]['moneda']] . "</td>";                             
                                echo "<td> " . LANG_from . " " . getDateForUser($plati[$i]['data_inceput']) . " " . LANG_pana_in . " " . getDateForUser($plati[$i]['data_sfarsit']) . "</td>";                            
                                if ($plati[$i]['achitat'] == 0) $status = LANG_Pending;
                                else $status = LANG_Aprooved;
                                echo "<td>" . $status . "</td>";                            
                                echo '<td><input type="button" value="'.LANG_Tiparire_factura.'" onClick="document.location = \'printFacturaClient.php?id='.$plati[$i]['id'].'\'"></td>';                            
                            echo "</tr>";
                        }                                                        
                    }
        echo "</table>";                                                                    
    echo "</div>";    
}

function sendEmailForNewUser($emailBody, $username, $password, $email) {
    $mail = new Mail();
    $mail->From = 'admin@onlinelogisitcs.eu';
    $mail->FromName = 'admin@onlinelogisitcs.eu';
    
    $mail->AddAddress($email);
    $mail->Subject = LANG_User_Email_Subject;
    
    $emailBody = str_replace("__USERNAME__", $username, $emailBody);
    $emailBody = str_replace("__PASSWORD__", $password, $emailBody);
    
    $mail->Body = $emailBody . LANG_Footer_Email;
    $mail->isHTML(true);
    //this should never fail, it's Google :D
    $mail->Send();
}

function sendEmailForResetPassword($toWhom, $emailBody, $new_password) {
    $mail = new Mail();
    $mail->From = 'admin@onlinelogisitcs.eu';
    $mail->FromName = 'admin@onlinelogisitcs.eu';
    
    $mail->AddAddress($toWhom);
    $mail->Subject = LANG_Schimba_parola;
    
    $emailBody = str_replace("__PASSWORD__", $new_password, $emailBody);    
    
    $mail->Body = $emailBody . LANG_Footer_Email;
    $mail->isHTML(true);
    //this should never fail, it's Google :D
    $mail->Send();	
}

function sendEmailForNewClient($bodyEmailClient, $bodyEmailUser, $signatureEmail, $client, $user) {
    $mail = new Mail();
    $mail->From = 'admin@onlinelogisitcs.eu';
    $mail->FromName = 'admin@onlinelogisitcs.eu';
    
    //send mail for client
    $tipAbonament = "";
    $cicluPlata = "";
    if ($client->tip_abon == 0) $tipAbonament = "5 utilizatori";
    if ($client->tip_abon == 1) $tipAbonament = "10 utilizatori";
    if ($client->tip_abon == 2) $tipAbonament = "Nr. utilizatori nelimitat";
    
    if ($client->ciclu_plata == 0) $cicluPlata = "3 luni";
    if ($client->ciclu_plata == 1) $cicluPlata = "6 luni";
    if ($client->ciclu_plata == 2) $cicluPlata = "12 luni";
    
    $mail->AddAddress($client->email);
    $mail->Subject = LANG_Client_Email_Subject;
    $bodyEmail = str_replace("__USERNAME__",        $user->username,    $bodyEmailClient);
    $bodyEmail = str_replace("__PASSWORD__",        $user->nonCryptedPassword, $bodyEmail);
    $bodyEmail = str_replace("__TIP_ABONAMENT__",   $tipAbonament,      $bodyEmail);
    $bodyEmail = str_replace("__CICLU_PLATA__",     $cicluPlata,        $bodyEmail);
    $bodyEmail .= $signatureEmail;
    $mail->Body = $bodyEmail . LANG_Footer_Email;
    $mail->isHTML(true);
    //this should never fail, it's Google :D
    $mail->Send();
    //end send mail for client
    
    //send mail for user
    $mail->ClearAddresses();
    $mail->AddAddress($user->email);
    $mail->Subject = LANG_User_Email_Subject;
    $bodyEmail = str_replace("__USERNAME__", $user->username, $bodyEmailUser);
    $bodyEmail = str_replace("__PASSWORD__", $user->nonCryptedPassword, $bodyEmail);
    $bodyEmail .= $signatureEmail;
    $mail->Body = $bodyEmail . LANG_Footer_Email;
    $mail->isHTML(true);
    //this should never fail, it's Google :D
    $mail->Send();
}

function sendEmailContactFromProgram($subject, $body) {
    $mail = new Mail();
    $mail->From = 'admin@onlinelogisitcs.eu';
    $mail->FromName = 'admin@onlinelogisitcs.eu';
    $mail->AddAddress("contact@onlinelogistics.eu");
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->isHTML(true);
    $mail->Send();
}

function sendEmailContactFromSite($subject, $body) {
    $mail = new Mail();
    $mail->From = 'admin@onlinelogisitcs.eu';
    $mail->FromName = 'admin@onlinelogisitcs.eu';
    $mail->AddAddress("contact@onlinelogistics.eu");
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->isHTML(true);
    $mail->Send();
}

function redirectOnError($errorFlag) {
	?>
	<script type="text/javascript">
		document.location = "error.php?error=" + <?php echo $errorFlag; ?>;
	</script>
	<?php
	exit();
}

function print_r_html($data,$return_data=false) {
    $data = print_r($data,true);
    $data = str_replace( " ","&nbsp;", $data);
    $data = str_replace( "\r\n","<br>\r\n", $data);
    $data = str_replace( "\r","<br>\r", $data);
    $data = str_replace( "\n","<br>\n", $data);

    if (!$return_data)
        echo $data;
    else
        return $data;
}

function print_r_toVar($data,$return_data=false) {
    $data = var_export($data,true);
    $data = str_replace( " ","&nbsp;", $data);
    $data = str_replace( "\r\n","<br>\r\n", $data);
    $data = str_replace( "\r","<br>\r", $data);
    $data = str_replace( "\n","<br>\n", $data);

    return $data;
}

function getAdresaAsString($adresa) {
	$ret = '';
    if ($adresa->adresa != '')
        $ret .= htmlspecialchars($adresa->adresa) . ', ';
    if ($adresa->cod_postal != '')
        $ret .= htmlspecialchars($adresa->cod_postal) . ', ';
    if ($adresa->oras != '')
        $ret .= htmlspecialchars($adresa->oras) . ', ';
    if ($adresa->judet != '')
        $ret .= htmlspecialchars($adresa->judet) . ', ';
    if ($adresa->tara != '')
        $ret .= htmlspecialchars($adresa->tara);
    
    return $ret;
}

function getAdreseForIncarcare($listaAdrese, $idAdresaIncarcare) {
	
    $ret = array();
    foreach($listaAdrese as $adresa) {
    	if (strpos($adresa->legatura_incarcare, (string)$idAdresaIncarcare) === false);
        else
            $ret[] = $adresa;
    }
    return $ret;
}

function getAdreseFaraIncarcare($listaAdrese) {
    $ret = array();
    foreach($listaAdrese as $adresa) {
    	if (empty($adresa->legatura_incarcare))
            $ret[] = $adresa;
    }
    return $ret;	
}

?>
